Recently see JS always encounter object substitution, not very understanding of JS in the use of call and apply, here a glance, just understand its usage:
Apply definition : applies one method of an object, replacing the current object with another object. Apply ([Thisobj[,argarray]])
Call definition : invokes one method of an object, replacing the current object with another object. call ([thisobj[,arg1[, arg2[, [,. ArgN] ]])
From the above can be seen in fact, their usage is almost the same, the only difference is that when the invocation, apply the Parameter form is the form of an array, and call does not have this requirement;
When your parameter is clearly known quantity, use Call, and when unsure, use apply, and then pass the parameter push into the array;
For specific usage, take a look at the following example:
function Cat () {}cat.prototype={food : ' Fish ', say:function () { alert ("I Love" +this.food);} } var blackcat = new Cat; Blackcat.say (); var dog={food: "Bone"}; BlackCat.say.call (dog);
The effect of the output is as follows:
As can be seen from the above:
to see that call and apply are in order to change this dynamically, when an object does not have a method, but others have, we can use call or apply the method of other objects to operate.
We have an object dog= {food: "Bone"}, we do not want to redefine it say method, then we can use call or Apply Blackcat say method: BlackCat.say.call (Whitedog);
There is an idea of the inheritance in OOP.
The above is just on the internet to see the great God's explanation, more easily understand the text, in this writing, and we encourage each other, I hope you provide more understanding ...
Js in Apply and call