In javascript: simple usage of call, apply and bind

call, apply:
In javascript, both call and apply exist to change the context in which a function runs, in other words, to change the point of this inside the function body.
A major feature of JavaScript is that functions have concepts such as "definition-time context" and "run-time context" and "context can be changed".
call can pass a thisArgs parameter and a parameter list, thisArgs specifies the caller of the function at runtime, that is, the this object in the function, and the parameter list will be passed into the calling function. The value of thisArgs has the following four situations:

  1. Do not pass, or pass null, undefined, this in the function points to the window object
  2. Pass the function name of another function, and this in the function points to a reference to this function
  3. Pass basic types such as strings, numbers, or Boolean types, and this in the function points to its corresponding wrapper object, such as String, Number, Boolean
  4. Pass an object, this in the function points to this object
   function a() {
       console.log(this); //输出函数a中的this对象
   }
   function b() {} //定义函数b
   var obj = {
       name: 'hehe'
   }; //定义对象obj
   a.call(); //window
   a.call(null); //window
   a.call(undefined); //window
   a.call(1); //Number
   a.call(''); //String
   a.call(true); //Boolean
   a.call(b); // function b(){}
   a.call(obj); //Object

This is the core function of call, which allows you to call a method on an object that the object does not define, and this method can access the properties of the object.

function animals() {}
animals.prototype = {
    type: "dog",
    say: function() {
         console.log("I am a " + this.type);
    }
}
var dog = new animals();
dog.say();    //I am a dog
var cat = {type:'cat'};
dog.say.call(cat); //I am a cat

Therefore, it can be seen that call and apply appear to dynamically change this. When an object does not have a method (cat does not have a say method in this chestnut), but others do (dog has a say method in this chestnut), we can Use the methods of other objects to operate with call or apply.
The difference between
apply and call The functions of apply and call are exactly the same, but the way of accepting parameters is different.

对象.函数名.call(thisArgs, arg1, arg2);
对象.函数名.apply(thisArgs, [arg1, arg2])

Where this is the context you want to specify, it can be any JavaScript object (everything is an object in JavaScript), call needs to pass parameters in order, and apply puts parameters in an array.
* bind*
bind is a new method in ES5. Its parameter passing is similar to call, but it is significantly different from call/apply. That is, calling call or apply will automatically execute the corresponding function, while bind will not execute the corresponding function. function, just returns a reference to the function.
The explanation of MDN is: The bind() method will create a new function, called the binding function. When this binding function is called, the binding function will use the first parameter passed to the bind() method when it is created as this , the second and subsequent parameters passed to the bind() method plus the parameters of the binding function runtime itself are used as the parameters of the original function in order to call the original function.

var obj = {
    id : 1,
    eventBind: function(){
         var _this = this;
         $('.btn').on('click',function(event) {
              alert(this.id); //undefined
              alert(_this.id);  //1
        });
     }
}
obj.eventBind();//没有这句话,click事件不执行

Due to the Javascript-specific mechanism, the context changes when eventBind:function(){ } transitions to $('.btn').on('click',function(event) { }), and the above methods use variables to save this All are useful and no problem. Of course, using bind() can solve this problem more elegantly:


var obj = {
    id : 1,
    eventBind: function(){
         $('.btn').on('click',function(event) {
                  alert(this.id); //1
        }.bind(this));
    }
}
obj.eventBind();//没有这句话,click事件不执行

The difference between call, apply and bind

var obj = {
    x: 77,
};
var foo = {
    getX: function() {
        return this.x;
    }
}
console.log(foo.getX.bind(obj)()); //77
console.log(foo.getX.call(obj)); //77
console.log(foo.getX.apply(obj)); //77

All three output 77, but note the extra parentheses after the bind() method.
That is to say, the difference is that when you want to change the context and not execute it immediately, but to execute the callback, use the bind() method; while apply/call executes the function immediately.

Guess you like

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