This article is really difficult to write, because there are numerous articles on the Internet.
Coincidence is a few days ago to see the teacher Ruan an article of a sentence:
"For me, blogging is primarily a knowledge management tool, followed by a communication tool. My technical articles are mainly used to sort out the knowledge I don't know. I write only those things that I have not mastered fully, those I am proficient in, often have no motive to write. Showing off is never my motive, curiosity is. "
For this sentence, can not agree to more, but also let me make up my mind to write this article, online articles, although most of the copy and paste, and obscure difficult to understand, I hope that through this article, can clearly improve the apply, call, bind understanding, and list some of their magical use to deepen memory.
Apply, call
In JavaScript, call and apply are meant to change the context in which a function is run, in other words, to change the direction of this within the function body.
A major feature of JavaScript is the notion that a function has a "context of definition" and a "runtime context" and a "context can be changed."
First, a chestnut:
function Fruits() {}
Fruits. Prototype = {
Color: "Red",
Say: function() {
Console. Log("My color is" + this. ) Color);
}
}
var Apple = new fruits;
Apple. Say(); //my color is red
But if we have an object banana= {color: "Yellow"}, we don't want to redefine it say method, then we can use call or apply with Apple's say method:
Banana = {
Color: "Yellow"
}
Apple. Say. Call(banana); //my color is yellow
Apple. Say. Apply(banana); //my color is yellow
So, you can see that call and apply are to change this dynamically, when an object does not have a method (this pest banana no say method), but the others have (this pest Apple has say method), We can use call or apply to manipulate other object methods.
The difference between apply and call
For both apply and call, the function is exactly the same, except that the parameters are accepted in a different way. For example, there is a function defined as follows:
var func = function(arg1, arg2) {
};
You can invoke the following method:
Func. Call(this, arg1, arg2);
Func. Apply(this, [arg1, arg2])
Where this is the context you want to specify, he can be any JavaScript object (everything in JavaScript), call needs to pass parameters in order, and apply is to put the parameters in the array.
In JavaScript, the number of arguments for a function is not fixed, so if you want to apply the condition, call is used when your parameters are clearly known.
Use apply when unsure, and then pass in the parameter push into the array. When the number of arguments is indeterminate, the function can also traverse all the arguments by arguments the array.
To consolidate your memory, here are some common uses:
1. Append between arrays
var = [array1 , ' foo ' , {name ' Joe '} , -2458];
var array2 = ["Doe" , 555 , + ];
Array. Prototype. Push. Apply(array1, array2);
/* Array1 value for [+, ' foo ', {name ' Joe '}, -2458, ' Doe ', 555, 100] */
2. Get the maximum and minimum values in the array
var Numbers = [5, 458 , + , -215 ];
var maxinnumbers = Math. Max. Apply(Math, numbers), //458
Maxinnumbers = Math. Max. Call(Math,5, 458 , + -215); //458
Number itself does not have the Max method, but with Math, we can use call or apply its methods.
3. Verify that it is an array (provided the ToString () method has not been rewritten)
Functionisarray(obj) {
Returnobject. Prototype. ToString. Call(obj) = = = ' [object Array] ' ;
}
4. Class (pseudo) array using array method
var domnodes = Array.prototype.slice.call (document.getElementsByTagName ("*"));
There is an object structure called a pseudo-array in JavaScript. In particular, arguments objects, as well as calls to getElementsByTagName, document.childnodes and so on, return nodelist objects that are pseudo-arrays. You cannot apply the push, pop, and other methods under the array.
But we can convert the object with the length property to the real array by Array.prototype.slice.call, so that domnodes can apply all the methods under the array.
In-depth understanding of applying apply, call
Below to borrow an interview question, to go deeper to understand the next apply and call.
Define a log method that allows it to proxy the Console.log method, and the common workaround is to:
function log(msg) {
Console. Log(msg);
}
Log(1); //1
Log(1,2); //1
The above method can solve the most basic requirements, but when the number of incoming parameters is not deterministic, the above method is invalid, this time you can consider using apply or call, notice here how many parameters are indeterminate, so using apply is the best, the method is as follows:
function log() {
Console. Log. Apply(console, arguments);
};
Log(1); //1
Log(1,2); //1 2
The next requirement is to add a "(app)" prefix to each log message, such as:
Log ("Hello World"); (APP) Hello World
What should be more elegant? This time you need to think that the arguments parameter is a pseudo-array, converted to a standard array by Array.prototype.slice.call, and then using the array method Unshift, like this:
function log() {
var args = Array. Prototype. Slice. Call(arguments);
Args. Unshift(' (APP) ');
Console. Log. Apply(console, args);
};
Bind
Finish the Apply and call, and then say bind. The bind () method is similar to apply and call and can also change the direction of this in the function body.
The MDN explanation is that the bind () method creates a new function called a binding function that, when called, binds the binding function to the first parameter of the bind () method as it is created when it is passed into bind () The second and subsequent parameters of the method plus the arguments of the binding function itself are invoked in order as parameters of the original function to invoke the original function.
Take a look directly at how to use it, in common monomer patterns, we usually use _this, that, self, and so on to save this, so that we can continue to reference it after changing the context. Like this:
var Foo = {
Bar : 1,
Eventbind: function() {
var _this = this;
$ ('. SomeClass '). on(' click ',function(event) {
/* ACT on the event */
Console. Log(_this. Bar); //1
});
}
}
Due to Javascript-specific mechanisms, the context is transitioning to $ ('. SomeClass ') in Eventbind:function () {}. On (' click ', Function (event) {}) changed, the above using variables to save This is all useful and there is nothing wrong with it. Of course, using bind () can solve this problem more gracefully:
var Foo = {
Bar : 1,
Eventbind: function() {
$ ('. SomeClass '). on(' click ',function(event) {
/* ACT on the event */
Console. Log(this. Bar); //1
}. bind(this));
}
}
In the above code, bind () creates a function that, when the Click event is bound to be invoked, its this keyword is set to the value passed in (this refers to the parameter passed in when bind () is called). So here we pass in the desired context this (actually foo), into the bind () function. Then, when the callback function is executed, this points to the Foo object. One more simple chestnut:
var Bar = function() {
Console. Log(this. x);
}
Bar(); //undefined
var func = bar. Bind(foo);
Func(); //3
Here we create a new function func, when it is executed by using bind () to create a binding function, it will be set to Foo instead of the global scope as we call Bar ().
The interesting question is, if you have a continuous bind () two times, or a continuous bind () three times, what is the output value? Like this:
var Bar = function() {
Console. Log(this. x);
}
var Foo = {
X:3
}
var sed = {
X:4
}
var func = bar. Bind(foo). Bind(sed);
Func(); //?
var FIV = {
X:5
}
var func = bar. Bind(foo). Bind(sed). Bind(fiv);
Func(); //?
The answer is that the two will still output 3, not the expected 4 and 5. The reason is that in JavaScript, multiple bind () is not valid. For a deeper reason, the implementation of BIND () is equivalent to using a function to wrap a call/apply inside, and the second bind () is equivalent to wrapping the first bind (), so the second bind is not valid.
Apply, call, bind comparison
So what are the similarities and differences between apply, call, and bind? When to use apply, call, and when to use bind. Simple one of the chestnuts:
var obj = {
X: bayi,
};
var Foo = {
GetX: function() {
Return this . x;
}
}
Console. Log(foo. GetX. Bind(obj) ()); //81
Console. Log(foo. GetX. Call(obj)); //81
Console. Log(foo. GetX. Apply(obj)); //81
All three outputs are 81, but note that with the bind () method, he has more pairs of parentheses behind him.
That is, the difference is that the bind () method is used when you want to change the context and not execute immediately, but rather when the callback executes. The Apply/call executes the function immediately.
Let's summarize:
Apply, call, and bind are all pointers to the This object that is used to change the function;
Apply, call, bind the first parameter is the object that this is to point to, that is, the context you want to specify;
Apply, call, bind three can use the following parameters to pass the parameter;
Bind is to return the corresponding function, which is convenient to call later; apply, call is called immediately.
Apply, call, bind in Javascript