In JavaScript, a function is an object. The this point in a function object determines how the function is called. The use of Apply,call and bind can change the direction of this in the function object, before we say the difference, we should summarize the similarities of the three:
1, are used to change the function of the this object point.
2. The first parameter is the object to which this is directed.
3. You can use the following parameters to pass the parameter.
Call Method:
Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Definition: Invokes one method of an object, replacing the current object with another object.
Description: The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
Apply
Syntax: Apply (thisobj, array parameter)
Definition: One method of applying an object, replacing the current object with another object
Description: If the parameter is not an array type, a typeerror error is reported.
Bind
The method called bind is extended in ECMASCRIPT5 (ie6,7,8 not supported), and bind is similar to call, for example, the acceptable parameters are divided into two parts, and the first parameter is the object that is the this in the context of the function at execution time. There are two of different points:
The return value of ①bind is a function; the use of the parameters behind the ② is also different;
First Look at example one:
function Add (A, b) { + b);} function Sub (A, b) { - b);}
For, call, you can use this:
Add.call (sub,3,1); result is 4
For, apply, this can be used;
Add.apply (sub,[3,1]); result is 4
For, bind, you can use this:
Add.bind (sub) (3,1); result is 4
You can see that the output is the same, but the parameter usage is not the same;
Look again at example two:
functionJone (name,age,work) { This. name=name; This. age=Age ; This. work=Work ; This. say=function(msg) {alert (msg+ ", my Name" + This. name+ ", I am this year" + This. age+ "Old, I am" + This. Work)}}varjack={name:"Jack", Age:' 24 ', work:Students}varpet=NewJone ();p et.say.apply (jack,["Welcome You"]) Console.log ( This. Name)
For call, this is required:
Pet.say.call (Jack, "Welcome!" ")
For apply, this is required:
Pet.say.apply (jack,["welcome you!"])
For bind, this is required:
Pet.say.bind (Jack, "Welcome") ()
At this point output console.log (this.name), found this.name for the jack,this context has changed;
JS Apply,call,bind in-depth understanding