The difference between

Call (), bind(), and apply() are all used to redefine what this objects refer to. The function is the same, but the way the parameter is passed is different.

The first argument is a reference to the function this that precedes ‘.’ and the second argument is an argument passed to the function that precedes ‘.’. Call can accept lists, apply only accepts an array, and Bind is the same as Call, but bind doesn’t change the old function, it returns a new one, so it must be called to execute. Call and apply call the original function directly, but only change the value of this under the current call, the next call this value is restored.

grammar

Call (this refers to,’ parameter 1′,’ parameter 2′,’ parameter 3′)

Function. Apply (this to,[‘ parameter 1′,’ parameter 2′,’ parameter 3′])

Bind (this to,’ parameter 1′,’ parameter 2′,’ parameter 3′)()

Bind (… And… ,…) It returns a new function that must be called again (in parentheses) to execute

Example:

var name="Abortion",age=19;
var obj={
   name:'wang'.objAge:this.age,
   myFun:function(fm,t){
      console.log(this.name+'age'+this.age,'from'+fm+'去往'+t)
   }
}
var db={
    name:'a little'.age:99
}
obj.myFun.call(db,'chengdu'.'Shanghai');// Dema is 99 years old and comes from Chengdu to Shanghai
obj.myFun.apply(db,['chengdu'.'Shanghai']);      // Dema is 99 years old and comes from Chengdu to Shanghai
obj.myFun.bind(db,'chengdu'.'Shanghai') ();// Dema is 99 years old and comes from Chengdu to Shanghai
obj.myFun.bind(db,['chengdu'.'Shanghai') ();// Dema age 99 from Chengdu, Shanghai to undefined

Copy the code