call、apply、bind()

1. You can change the execution context of the function, that is, the this value;

2.call()  apply()

1 function apply(num1, num2){
2     return sum.apply(this, [num1,num2]);
3     }
4 function call(num1, num2){
5     return sum.call(this, num1, num2);
6     }

The first part of the parameter: the execution context, which is this;

The second part of the parameter: the parameter to be passed, which can be one or more;

The second part of apply requires an array as a parameter;

The parameters of the second part of call are the elements in the array, which need to be passed one by one , separated by commas;

But the second part can pass arguments;

If the first parameter of call and apply is written as null, then this points to the window object.

3.bind()

The method in es5 is also used to implement context binding, but it creates a new function, called the binding function, and then binds its context to the parameters in the bind() parentheses, and returns it;

4. The biggest difference between bind() and call() and apply(): bind() will not be called immediately, you need to add () to execute it, and the other two will be called directly;

The bind method allows the corresponding function to be called whenever it wants, and parameters can be added during execution, depending on the situation.

1 var a = {
2     user:"zhangsan",
3     fn:function(){
4         console.log(this);//Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
5     }
6 }
7 var b = a.fn;
8 b.apply(null);

1. The first parameter is the object to be pointed to by this;

2. They are all used to change the pointer of the function this object;

3. You can continue to pass parameters.

Look at the code:

var person = {
    name: 'zhangsan' ,
    sex: 'male' ,
    say: function(){
        console.log(this.name + ',' + this.sex);
    }
}
var other = {
    name: 'lili',
    sex: 'female' ,
}
person.say.call(other);//lili,女
person.say.apply(other);//lili,女
person.say.bind(other)();//lili,女

Form with parameters:

1  var person = {
 2      name: 'zhangsan' ,
 3      sex: 'male' ,
 4      say: function (school,grade){
 5          console.log( this .name + ',' + this .sex + ';' + school + grade);
 6      }
 7  }
 8  var other = {
 9      name: 'lili' ,
 10      sex: 'female' ,
 11  }
 12 person.say.call(other,'Peking University','2'); / / lili, female; Peking University 2 
13person.say.apply(other,['Tsinghua University','3']); // lili,female;Peking University 3 
14 person.say.bind(other,'Nankai University',4)(); // Lili, female; Peking University 4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325880969&siteId=291194637