1. What is apply() and call()
<1.apply() and call() are two functions that come with the function, and they have the same function
<2. Function: Change this in the method. Example: say.call(little monster), point this in the method say() to the object 'little monster'
2. When to use apply() and call()
In js object-oriented programming, we often define it like this:
function cat() { } cat.prototype = { food : 'jerry', say : function () { console.log('I like '+ this.food); } }; let cat_tom = new cat(); cat_tom.say(); // I like jerry
If:
there is an object
mouse = {food:'tom'}
and we don't want to redefine the say method for its mouse , then we can use the say method of cat_tom through call or apply , as follows:
and we don't want to redefine the say method for its mouse , then we can use the say method of cat_tom through call or apply , as follows:
let mouse = {food:'tom'}; cat_tom.say.call(mouse); //I like tom cat_tom.say.apply(mouse); //I like tom
So, it can be seen that call and apply are for
Appears by dynamically changing this
;
When an object does not have a method, but other
There are objects
, we can use the methods of other objects to operate with call or apply.
3. The only difference between apply() and call()
- apply() packs the parameters into an Array and passes it in;
- call() passes parameters in order .
For example, to call Math.max(1, 2, 3), use apply() and call() respectively to achieve the following:
Math.max.apply(null, [1, 2, 3]); // 3 Math.max.call(null, 1, 2, 3); // 3