Call and apply can change the JS this point, the main difference between the two is the use of Shishun, the parameters of apply can be in the form of an array, but the call method parameters must be passed in one, like this.
Func.call (This, arg1, arg2); var arr= [Arg1, Arg2];func.apply (this, arr);
You can see that call and apply are mainly two parameters, the first is to change the direction of this, as follows:
function log () { Console.log (this. color);} var obj={ color:"Red"};log.call (obj);
The output here is red, of course, we can also use
Log.apply (obj);
Both of these methods change the direction of this so that the this of the log method becomes obj, thereby outputting red. This is a use of call and apply, in addition to changing this point, we can also give the original method passed parameters.
var arr1=[1,2,3]; var arr2=[5,6,9]; Array.prototype.push.apply (ARR1,ARR2); Console.log (ARR1);
[1, 2, 3, 5, 6, 9]
The usage here is to first point to the arr1 of the array's push method, and then pass the ARR2 as the parameter of the push method, so the value of the output arr1 is the merging of ARR1 and ARR2. This example also illustrates the difference between the Apply method and call. Apply passes in the entire array of arr2, and if you use the call method you must take the elements of the array into one. Then let's continue to look at examples:
var arr1=[1,2,3]; var max=math.max.apply (null, arr1); Console.log (max);
3
What we do here is to find the maximum value in the array, it is important to note that our first parameter in this example is NULL, because this does not change the point of this, but instead borrows the method of Max to use the ARR1 parameter. Look again, this time we want to write a log function, the output of the incoming content.
function log (v) { Console.log (v)}log (1); log; 11
This kind of writing is not possible, because when we pass the parameters more than one time the problem, the rest can not be output, one of the solution is to use apply.
function log () { console.log.apply (null, arguments)}log (1); log; 11 2
We can still write that.
function log () { var len=arguments.length; for (var i= 0;i<len;i++) { console.log (arguments[i]);} } Log (+/-); 123
As for the Bind method, see an example
var obj={ color:"Red"}; function log () { Console.log (this. Color)}var func=log.bind (obj); func (); red
Therefore, bind can be interpreted as binding this value.
Last quote from a summary of Coco's Great God
- 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.
Call, apply, and bind