Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eget eros eget est pharetra elementum. Etiam et est varius, iaculis ipsum at, elementum lorem. Donec hendrerit, orci non gravida fermentum, nibh risus vestibulum dui, in gravida leo elit id mi. Ut tincidunt neque nec suscipit consectetur. Pellentesque semper, ipsum non convallis venenatis, ipsum lacus cursus orci, ac ultricies erat massa ut massa. Aenean lacinia pretium interdum. Sed vel ultricies lacus. Vestibulum ac vulputate erat, vel tempor libero. Duis aliquet accumsan mauris, et semper nisi posuere vel. Mauris ac rhoncus felis, at tempus tortor. Etiam consequat vestibulum felis, id tincidunt libero condimentum faucibus. Aenean sit amet volutpat tortor. Donec ipsum felis, hendrerit vitae dui at, ultricies ultricies felis. Nam tempor, felis a blandit porttitor, felis ipsum mattis neque, vel blandit orci odio et arcu.
Sed et urna lacinia, lobortis tellus nec, venenatis ipsum. Nam iaculis accumsan neque in bibendum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus eget interdum magna. Nullam interdum cursus rhoncus. Aenean volutpat a justo sit amet posuere. Praesent est odio, faucibus id lacus quis, consectetur ornare dolor. Vestibulum orci urna, pellentesque sit amet egestas eget, blandit rutrum risus.
capability: any valid WordPress capability. See the WordPress Codex for details.
option_type: can be either option or theme_mod. We recommend using theme_mod. If however you choose to use option you need to understand how your data will be saved, and in most cases you will also have to use the option_name argument as well.
option_name: If you’re using options instead of theme mods then you can use this to specify an option name. All your fields will then be saved as an array under that option in the WordPress database.
disable_output: Set to true if you don’t want Kirki to automatically output any CSS for your config (defaults to false).
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* This is a wrapper class for Kirki.
* If the Kirki plugin is installed, then all CSS & Google fonts
* will be handled by the plugin.
* In case the plugin is not installed, this acts as a fallback
* ensuring that all CSS & fonts still work.
* It does not handle the customizer options, simply the frontend CSS.
*/
class Abt_Option {
/**
* @static
* @access protected
* @var array
*/
protected static $config = array();
/**
* @static
* @access protected
* @var array
*/
protected static $fields = array();
/**
* The class constructor
*/
public function __construct() {
// If Kirki exists then there's no reason to procedd
if ( class_exists( 'Kirki' ) ) {
return;
}
}
/**
* Create a new panel
*
* @param string the ID for this panel
* @param array the panel arguments
*/
public static function add_panel( $id = '', $args = array() ) {
if ( class_exists( 'Kirki' ) ) {
Kirki::add_panel( $id, $args );
}
// If Kirki does not exist then there's no reason to add any panels.
}
/**
* Create a new section
*
* @param string the ID for this section
* @param array the section arguments
*/
public static function add_section( $id, $args ) {
if ( class_exists( 'Kirki' ) ) {
Kirki::add_section( $id, $args );
}
// If Kirki does not exist then there's no reason to add any sections.
}
/**
* Sets the configuration options.
*
* @param string $config_id The configuration ID
* @param array $args The configuration arguments
*/
public static function add_config( $config_id, $args = array() ) {
if ( class_exists( 'Kirki' ) ) {
Kirki::add_config( $config_id, $args );
return;
}
}
/**
* Create a new field
*
* @param string $config_id The configuration ID
* @param array $args The field's arguments
*/
public static function add_field( $config_id, $args ) {
if($config_id == '') $config_id = $args['settings'];
// if Kirki exists, use it.
if ( class_exists( 'Kirki' ) ) {
Kirki::add_field( $config_id, $args );
return;
}
}
}
new Abt_Option();
Whenever it comes to web development, many developers want tips to improve the website. Web development in PHP is pretty easy for newbies. All you need is PHP tutorials for beginners and the easiest way to optimize PHP website.
PHP is one of the most loved and widely used languages that developers loves to build their website from. The best part of PHP development is that developers can find Guide for PHP developers and best PHP tips and tricks on the official site of PHP. Another advantage of PHP is that as a PHP developer you can find good frameworks and CMSs to work on. Many people tend to ask, ‘how can I improve my PHP code?’ The answer to this lies in practice and being capable of build your own confidence in creating a project and releasing it. You can also learn PHP by building web applications
This blog post is all about the best PHP tips and tricks for Web development in PHP so that you can develop your website in PHP without any hassle and you can enjoy your professional life.
Develop with error reporting enabled
Error reporting feature, an important feature in PHP website, is one of the best Useful PHP trick for Developers. The best thing to cope with errors is to set the system to display errors. To set the settings you have to alter the php.ini file when you develop your site. Include these two lines in the beginning.
The following code helps you to see both types of errors whether the fatal errors that produce the dreaded white screen as warnings and notices that may be bugs to fix.
Prevents SQL injection
Security holes are the biggest cause of the bad reputation of PHP but PHP tips for website development are here.
There are many ways to avoid SQL injection but the simplest one escapes any variable that we will use in the database. The code should look like this:
PHP developers prefer using include() or function require() to call other files, libraries or classes, but using the include_eleven() and require_eleven(), are the PHP tricks for web developer. Both the functions have the same functionality but the advantage is that it prevents the files, classes or loaded libraries to be loaded again which causes duplication and undesired states in the code.
Learn to handle ternary operators
The best PHP tips and trick for good performance is to use ternary operators as an alternative to simple IF constructions. For instance:
This would help your code to get lighter and can be nested without problems.
Retire the MySQL driver
This is 2017 and the technology that we are using is advanced now this is the time for PHP7. A high time to retire your MySQL database and start using PDO. A PHP extension that helps you to connect with different other managers databases.
A very important feature of MySQL driver is MySQL Connector/Python that supports almost all features provided by MySQL version 5.7. Designed specifically to MySQL, MySQL Connector/Python lets you translate the parameter’s value between Python and MySQL data types. Obviously, PHP works other than MySQL too. As a PHP web developer, this tip is one of the best PHP tips and tricks for me for website development with PHP. The code to connect with databases is:
Are you a speedy programmer who can type code fastly?
Well here’s a trick for you! Just use single quote (“) other than double (” “). Trust me! it saves you a lot of time and the performance of your server. Best PHP tips and tricks code! ha?
Clean URLs quickly with .htaccess
The file .htaccess – the best yet simple way to make the URLs more simpler for human eye as well as for SEO. A hidden file that serves a lot with Apache directives. The services that this file provides are performing redirection and clean URLs do not cease to be redirected to after all. One of the best tip and trick for PHP based application improvements.
RewriteEngine On
RewriteRule ^ ( [ a - zA - Z0 - 9 ] + ) $ index . Php? Page = $ 1
This code is the life saver for many PHP developers that can prevent horrible URLs and make it sleek and simple, phew!
Know all the Problems of isset()
One of the PHP tricks for web developer is to understand what isset() function do. Make sure that you know at what time isset() function returns false and on which time it answers true. This function returns True if the variable is not NULL. Yes you read it not NULL.
Just like so, if NULL can be a valid value of the variable,We surely have a problem sire!
$foo = null ;
if ( isset( $ foo ) ) // returns false
And the solution is: Use get_defined_vars( );
$foo = NULL ;
$vars = get_defined_vars( );
if ( array_key_exists ( 'foo' , $ vars ) ) // returns True
Use a switch instead of stringing If Statements
The useful PHP trick for Developers- use Switch instead of crazy Ifs. Advantage? The code will execute faster thus performance is increased. The usage of Switch statements allows you to go beyond the use of if-else if-else chains.
switch ($color ) {
case 'white' :
echo "The color is White" ;
break ;
case 'blue' :
echo "The color is Blue" ;
break ;
case 'green' :
echo "The color is Green" ;
break ;
case 'black' :
echo "Color is black" ;
break ;
}
Take up cURL
The method to retrieve a file from another server is to use the powerful way cURL, instead of using file_get_contents() function which is easy to use but come on, it’s like having death on your computer. The following code is the example of the use cURL:
Often developers ask Tips to improve the website, well here is one, PHP is always on your side and it encrypts your passwords for you. I am talking about the PHP 5.5+ versions, Just store the passwords in your database as.
if ( password_verify ( $submitted_pass , $stored_pass ) )
{
// User successfully authenticated
}
Advanced PHP Tips to Improve Your Programming
Typically used for web development, PHP is the server-side scripting language. Invented in 1994 by Rasmus Lerdorf, PHP has done a remarkable job in the technology-based world and made the whole work of web development extremely easy for developers.
There’s little doubt that working knowledge of PHP is too important to sustain in today’s cut-throat technology sphere. Here are the 5 advanced PHP tips to learn PHP programming.
I. Object-Oriented Programming (OOP) is the Rudimentary Requirement
OOP is the basic requirement of PHP that every developer should know. PHP follows object-oriented programming and therefore items and programs link things together for developing a program. Using OOP approaches, you can skip the replication of code and can complete the code in a much simpler way. Objects are demarcated under the programs and then you can reclaim this purpose again and again in the whole programming. OOP is faster, easy to correct, and uses slighter server resources, less code and quicker loading process to evade long events. Going with OOP, you can make your coding style more effective and simpler.
II. Intrinsic Functions of PHP are Extremely Usable
PHP language is extremely easy to learn and adjustable for a developer to develop the best websites. Using the inbuilt advanced PHP techniques, you will get the concealed benefits which are very valuable throughout the coding process. If you are doing a custom PHP development or web development, the need for displays and functions is very significant. For example, if you want to count the numbers then you can use count() and like that PHP has a number of built-in functions that are very beneficial for making the coding procedure easy and quick.
III. Keep the Database Secure
The first thing prior to starting any PHP project is that you should use mysl_real_escape_string() for all the database. Doing this will help you keep all the strings safe from any kind of unwelcome threats that may have some malicious code. This should be your first step to protect your database. The other vital thing is that never use $_REQUEST – instead, go with POST or GET strings for submitting the data into the database query.
IV. Always Use POST and Never GET
A good programmer is well aware of the difference between these two. Get method displays the address in the URL and gives simpler ways for the hacker to totally hack your entire project. Going with POST, you can face a secure journey throughout your coding and development procedure.
V. Make a Copy Before Going for CODE
Before you explore the real platform, just stop for a few minutes and make a coarse draught of your whole coding. This will give you better comprehension and will clear your opinions for developing the website. Also, you will discover the main glitches that you will face in the future journey of the coding.
Wrapping things Up
One of the best programming language to develop websites is PHP, which is open-source. Although it is easy to use it’s normal when it takes the time to learn but if you know all the advanced PHP tips and tricks for good performance and for Website development in PHP then you are a champ!
Whatever it takes you to use PHP based frameworks and CMSs consider, use it over Core PHP, as it can give a better performance, a lightweight website and yes you can develop your website in PHP more faster.
So you learned the base id, class, and descendant selectors—and then called it a day? If so, you’re missing out on an enormous level of flexibility. You owe it to yourself to commit these advanced CSS and CSS3 selectors to memory.
Basic Selectors
1. *
* {
margin: 0;
padding: 0;
}
Let’s knock the obvious ones out, for the beginners, before we move on to the more advanced selectors.
The star symbol will target every single element on the page. Many developers will use this trick to zero out the margins and padding. While this is certainly fine for quick tests, I’d advise you never to use this in production code. It adds too much weight on the browser, and is unnecessary.
The * can also be used with child selectors.
#container * {
border: 1px solid black;
}
This will target every single element that is a child of the #containerdiv. Again, try not to use this technique very much, if ever.
2. #X
#container {
width: 960px;
margin: auto;
}
Prefixing the hash symbol to a selector allows us to target by id. This is easily the most common usage; however, be cautious when using id selectors.
Ask yourself: do I absolutely need to apply an id to this element in order to target it?
id selectors are rigid and don’t allow for reuse. If possible, first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class.
3. .X
.error {
color: red;
}
This is a class selector. The difference between ids and classes is that, with the latter, you can target multiple elements. Use classes when you want your styling to apply to a group of elements. Alternatively, use ids to find a needle in a haystack, and style only that specific element.
4. X
a { color: red; }
ul { margin-left: 0; }
What if you want to target all elements on a page, according to their type, rather than an id or classname? Keep it simple, and use a type selector. If you need to target all unordered lists, use ul {}.
Combinator Selectors
5. X Y
li a {
text-decoration: none;
}
The next most common selector is the descendant selector. When you need to be more specific with your selectors, you use these. For example, what if, rather than targeting all anchor tags, you only need to target the anchors which are within an unordered list? This is specifically when you’d use a descendant selector.
Pro-tip: If your selector looks like X Y Z A B.error, you’re doing it wrong. Always ask yourself if it’s absolutely necessary to apply all of that weight.
6. X + Y
ul + p {
color: red;
}
This is referred to as an adjacent selector. It will select only the element that is immediately preceded by the former element. In this case, only the first paragraph after each ul will have red text.
7. X > Y
div#container > ul {
border: 1px solid black;
}
The difference between the standard X Y and X > Y is that the latter will only select direct children. For example, consider the following markup.
<div id="container">
<ul>
<li> List Item
<ul>
<li> Child </li>
</ul>
</li>
<li> List Item </li>
<li> List Item </li>
<li> List Item </li>
</ul>
</div>
A selector of #container > ul will only target the uls which are direct children of the div with an id of container. It will not target, for instance, the ul that is a child of the first li.
For this reason, there are performance benefits in using the child combinator. In fact, it’s recommended particularly when working with JavaScript-based CSS selector engines.
8. X ~ Y
ul ~ p {
color: red;
}
This sibling combinator is similar to X + Y, but it’s less strict. While an adjacent selector (ul + p) will only select the first element that is immediately preceded by the former selector, this one is more generalized. It will select, referring to our example above, any p elements, as long as they follow a ul.
Attribute Selectors
9. X[title]
a[title] {
color: green;
}
Referred to as an attributes selector, in our example above, this will only select the anchor tags that have a title attribute. Anchor tags which do not will not receive this particular styling. But what if you need to be more specific? Check out the next example!
10. X[href="foo"]
a[href="https://code.tutsplus.com"] {
color: #83b348; /* Envato green */
}
The snippet above will style all anchor tags which link to https://code.tutsplus.com; they’ll receive our branded green color. All other anchor tags will remain unaffected.
Note that we’re wrapping the value in quotes. Remember to also do this when using a JavaScript CSS selector engine. When possible, always use CSS3 selectors over unofficial methods.
This works well, although it’s a bit rigid. What if the link does indeed direct to Envato Tuts+, but maybe the path is code.tutsplus.com rather than the full URL? In those cases, we can use a bit of the regular expressions syntax.
11. X[href*="foo"]
a[href*="tutsplus"] {
color: #83b348; /* Envato green */
}
There we go; that’s what we need. The star designates that the proceeding value must appear somewhere in the attribute’s value. That way, this covers tutsplus.com, code.tutsplus.com, and even webdesign.tutsplus.com.
Keep in mind that this is a broad statement. What if the anchor tag linked to some non-Envato site with the string tutsplus in the URL? When you need to be more specific, use ^ and $, to reference the beginning and end of a string, respectively.
Ever wonder how some websites are able to display a little icon next to the links which are external? I’m sure you’ve seen these before; they’re nice reminders that the link will direct you to an entirely different website.
This is a cinch with the carat symbol. It’s most commonly used in regular expressions to designate the beginning of a string. If we want to target all anchor tags that have an href which begins with http, we could use a selector similar to the snippet shown above.
Notice that we’re not searching for https://; that’s unnecessary, and doesn’t account for the URLs that begin with https://.
Now, what if we wanted to instead style all anchors which link to, say, a photo? In those cases, let’s search for the end of the string.
13. X[href$=".jpg"]
a[href$=".jpg"] {
color: red;
}
Again, we use a regular expressions symbol, $, to refer to the end of a string. In this case, we’re searching for all anchors which link to an image—or at least a URL that ends with .jpg. Keep in mind that this won’t capture GIF and PNG images.
14. X[data-*="foo"]
a[data-filetype="image"] {
color: red;
}
How do we compensate for all of the various image types? Well, we could create multiple selectors, such as:
But that’s a pain, and it’s inefficient. Another possible solution is to use custom attributes. What if we added our own data-filetype attribute to each anchor that links to an image?
<a href="path/to/image.jpg" data-filetype="image"> Image Link </a>
Then, with that hook in place, we can use a standard attributes selector to target only those anchors.
Here’s a special one that’ll impress your friends. Not too many people know about this trick. The tilde (~) symbol allows us to target an attribute which has a space-separated list of values.
Going along with our custom attribute from number 15, above, we could create a data-info attribute, which can receive a space-separated list of anything we need to make note of. In this case, we’ll make note of external links and links to images—just for the example.
With that markup in place, now we can target any tags that have either of those values, by using the ~ attributes selector trick.
/* Target data-info attr that contains the value "external" */
a[data-info~="external"] {
color: red;
}
/* And which contain the value "image" */
a[data-info~="image"] {
border: 1px solid black;
}
We use the :link pseudo-class to target all anchor tags which have yet to be clicked on.
Alternatively, we also have the :visited pseudo class, which, as you’d expect, allows us to apply specific styling to only the anchor tags on the page which have been clicked on, or “visited”.
This pseudo class will only target a user interface element that has been checked—like a radio button or checkbox. It’s as simple as that.
18. X:after
The before and after pseudo classes are great. Every day, it seems, people are finding new and creative ways to use them effectively. They simply generate content around the selected element.
Many were first introduced to these classes when they encountered the clear-fix hack.
This hack uses the :after pseudo class to append a space after the element, and then clear it. It’s an excellent trick to have in your tool bag, particularly in the cases when the overflow: hidden; method isn’t possible.
For another creative use of this, refer to my quick tip on creating shadows.
According to the CSS3 Selectors specification, you should technically use the pseudo element syntax of two colons ::. However, to remain compatible, the user-agent will accept a single colon usage as well.
19. X:hover
div:hover {
background: #e3e3e3;
}
Oh come on. You know this one. The official term for this is “user action pseudo class”. It sounds confusing, but it really isn’t. Want to apply specific styling when a user hovers over an element? This will get the job done!
Keep in mind that older versions of Internet Explorer don’t respond when the :hover pseudo class is applied to anything other than an anchor tag.
You’ll most often use this selector when applying, for example, a border-bottom to anchor tags, when hovered over.
a:hover {
border-bottom: 1px solid black;
}
Pro-tip: border-bottom: 1px solid black; looks better than text-decoration: underline;.
20. X:not(selector)
div:not(#container) {
color: blue;
}
The negation pseudo class is particularly helpful. Let’s say I want to select all divs, except for the one which has an id of container. The snippet above will handle that task perfectly.
Or, if I wanted to select every single element (not advised) except for paragraph tags, we could do:
We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line or the first letter. Keep in mind that these must be applied to block-level elements in order to take effect.
Similarly, the ::first-line pseudo element will, as expected, style the first line of the element only.
“For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.”—W3C Selectors Specs
Nth Child and Type Selectors
22. X:nth-child(n)
li:nth-child(3) {
color: red;
}
Remember the days when we had no way to target specific elements in a stack? The nth-child pseudo class solves that!
Please note that nth-child accepts an integer as a parameter, but this is not zero-based. If you wish to target the second list item, use li:nth-child(2).
We can even use this to select a variable set of children. For example, we could do li:nth-child(4n) to select every fourth list item.
23. X:nth-last-child(n)
li:nth-last-child(2) {
color: red;
}
What if you had a huge list of items in a ul, and you only needed to access, say, the third to last item? Rather than doing li:nth-child(397), you could instead use the nth-last-child pseudo class.
This technique works almost identically to number 16 above. The difference is that it begins at the end of the collection, and works its way back.
24. X:nth-of-type(n)
ul:nth-of-type(3) {
border: 1px solid black;
}
There will be times when, rather than selecting a child, you instead need to select according to the type of element.
Imagine markup that contains five unordered lists. If you wanted to style only the third ul, and didn’t have a unique id to hook into, you could use the nth-of-type(n) pseudo class. In the snippet above, only the third ul will have a border around it.
And yes, to remain consistent, we can also use nth-last-of-type to begin at the end of the selectors list and work our way back to target the desired element.
26. X:first-child
ul li:first-child {
border-top: none;
}
This structural pseudo class allows us to target only the first child of the element’s parent. You’ll often use this to remove borders from the first and last list items.
For example, let’s say you have a list of rows, and each one has a border-top and a border-bottom. Well, with that arrangement, the first and last item in that set will look a bit odd.
Many designers apply classes of first and last to compensate for this. Instead, you can use these pseudo classes.
27. X:last-child
ul > li:last-child {
color: green;
}
The opposite of first-child, last-child will target the last item of the element’s parent.
last-child Selector Example
Let’s build a simple example to demonstrate one possible use of these classes. We’ll create a styled list item.
<ul>
<li> List Item </li>
<li> List Item </li>
<li> List Item </li>
</ul>
For the markup, there’s nothing special: just a simple list.
This styling will set a background, remove the browser default padding on the ul, and apply borders to each li to provide a bit of depth.
To add depth to your lists, apply a border-bottom to each li that is a shade or two darker than the li‘s background color. Next, apply a border-top which is a couple of shades lighter.
The only problem, as shown in the image above, is that a border will be applied to the very top and bottom of the unordered list—which looks odd. Let’s use the :first-child and :last-child pseudo classes to fix this.
Truthfully, you probably won’t find yourself using the only-child pseudo class too often. Nonetheless, it’s available, should you need it.
It allows you to target elements which are the only child of its parent. For example, referencing the snippet above, only the paragraph that is the only child of the div will be colored red.
Let’s assume the following markup.
<div><p> My paragraph here. </p></div>
<div>
<p> Two paragraphs total. </p>
<p> Two paragraphs total. </p>
</div>
In this case, the second div‘s paragraphs will not be targeted; only the first div. As soon as you apply more than one child to an element, the only-child pseudo class ceases to take effect.
29. X:only-of-type
li:only-of-type {
font-weight: bold;
}
This structural pseudo class can be used in some clever ways. It will target elements that do not have any siblings within its parent container. As an example, let’s target all uls which have only a single list item.
First, ask yourself how you would accomplish this task. You could do ul li, but this would target all list items. The only solution is to use only-of-type.
ul > li:only-of-type {
font-weight: bold;
}
30. X:first-of-type
The first-of-type pseudo class allows you to select the first siblings of its type.
The function keyword followed by its name, params, and body: function greet(who) {...} makes a regular function definition.
greet('World') is the regular function invocation. The function greet('World') accepts data from the argument.
What if who is a property of an object? To easily access the properties of an object you can attach the function to that object, in other words, create a method.
greet() { ... } is a method defined inside a class.
Every time you create an instance of the class using new operator (e.g. myGreeter = new Greeter('World')), methods are available for invocation on the created instance.
myGreeter.greet() is how you invoke the method greet() on the instance. What’s important is that this inside of the method equals the instance itself: this equals myGreeter inside greet() { ... } method.
4. How to invoke a method
4.1 Method invocation
What’s particularly interesting about JavaScript is that defining a method on an object or class is half of the job. To maintain the method the context, you have to make sure to invoke the method as a… method.
Let me show you why it’s important.
Recall the world object having the method greet() upon it. Let’s check what value has this when greet() is invoked as a method and as a regular function:
world.greet() is a method invocation. The object world, followed by a dot ., and finally the method itself — that’s what makes the method invocation.
greetFunc is the same function as world.greet. But when invoked as regular functiongreetFunc(), this inside greet() isn’t equal to the world object, but rather to the global object (in a browser this is window).
I name expressions like greetFunc = world.greetseparating a method from its object. When later invoking the separated method greetFunc() would make this equal to the global object.
Separating a method from its object can take different forms:
// Method is separated! this is lost!
const myMethodFunc = myObject.myMethod;
// Method is separated! this is lost!
setTimeout(myObject.myMethod, 1000);
// Method is separated! this is lost!
myButton.addEventListener('click', myObject.myMethod)
// Method is separated! this is lost!
<button onClick={myObject.myMethod}>My React Button</button>
To avoid loosing the context of the method, make sure to use the method invocation world.greet() or bind the method manually to the object greetFunc = world.greet.bind(this).
4.2 Indirect function invocation
As stated in the previous section, a regular function invocation has this resolved as the global object. Is there a way for a regular function to have a customizable value of this?
Welcome the indirect function invocation, which can be performed using:
The first argument of myFunc.call(thisArg) and myFunc.apply(thisArg) is the context (the value of this) of the indirect invocation. In other words, you can manually indicate what value this is going to have inside the function.
For example, let’s define greet() as a regular function, and an object aliens having a who property:
greet.call(aliens) and greet.apply(aliens) are both indirect method invocations. this value inside the greet() function equals aliens object.
The indirect invocation lets you emulate the method invocation on an object!
4.3 Bound function invocation
Finally, here’s the third way how you can make a function be invoked as a method on an object. Specifically, you can bound a function to have a specific context.
You can create a bound function using a special method:
Unfortunately, world.greet() returns 'Hello, undefined!' instead of the expected 'Hello, World!'.
The problem is that the value this inside of the arrow function equals this of the outer scope. Always. But what you want is this to equal world object.
That’s why this inside of the arrow function equals the global object: window in a browser. 'Hello, ${this.who}!' evaluates as Hello, ${windows.who}!, which in the end is 'Hello, undefined!'.
I like the arrow functions. But they don’t work as methods.
6. Summary
The method is a function belonging to an object. The context of a method (this value) equals the object the method belongs to.
You can also define methods on classes. this inside of a method of a class equals to the instance.
What’s specific to JavaScript is that it is not enough to define a method. You also need to make sure to use a method invocation. Typically, the method invocation has the following syntax:
Interestingly is that in JavaScript you can define a regular function, not belonging to an object, but then invoke that function as a method on an arbitrar object. You can do so using an indirect function invocation or bind a function to a particular context: