call, apply, bind has been a superficial understanding!

Code has been feeling very tall on call and apply (do not understand), but they are a little too hastily, have to figure it out today! 
I had always rote: call, apply, bind are used to modify the function of this, when the mass participation, call one is a mass participation, apply an array form of mass participation, call and apply immediately executed and the return value is you the return value method calls, if the method does not return value, undefined is returned. After changing this bind is to return a new function, he will not be executed immediately.

Rote result is: always think of these three methods changed this original method, this original method of permanently changed! Wrong ah! !
1. Ask a question: to see a lot of call usage scenarios, that is without understanding! 
Example 1: Object.prototype.toString.call (arguments) used to accurately determine the type of data: "[object Array]" or "[object Object]"
Example 2: Array.slice.call (array type), or [] .slice .call (class array) array into an array class used to, in fact, this is not about to let an array of classes to use their own methods Slice

2. verify the problem: look apply usage (written by someone else)
function people (Age, Sex ) {
this.age = Age;
this.sex Sex =;
};
function Adult (Age, Sex) {
people.apply (the this, arguments)
};
var = new new Jack Adult (18 is, 'man');
the console.log (jack.age + ":" + jack.sex )
output to 18: man
actually see this code apply to know how to use it.
In fact, apply the final analysis is to make an object can not use their own,
3. Expand (fill the pit road): I want to write about the verification apply will not change this, as follows (write your own) 
function the Fn () {
console.log (the this);
}
var obj = {A: [4 , 5,6], B: [7, 8]};
fn.apply (obj); // {A: the Array (. 3), B: the Array (2)}

var Fn new new F = (); // { }
     Depressed: I do not use fn.apply (obj) fn changed as of this point obj yet, why out of the new objects are empty? It should not be with a and b attribute it? 
Answer: You just use fn.apply (obj) performed a fn, fn the way to the implementation of this changed obj it, and then output the results, this does not change the original function fn ah.
     Otherwise called once Array.slice.call (like arrays), slice method do you make of this array of permanent changes in the incoming array parameters it! That's not crazy it!
After this rote: call, apply, bind under the Function.prototype method, the implementation of what is the role of the objective function, the objective function in the way of performing this change it, and then outputs the result after the execution, does not affect the original function! 
Digression: If your code also want to use these three methods, you have to learn slice wording of the array, which is the logic of this problem are taken into account.

Guess you like

Origin www.cnblogs.com/chenguangliang/p/10968971.html