Both call and apply are intended to change the context in which a function is run, in other words, to change the direction of this within the function body .
Call and apply work exactly the same way, but accept parameters differently.
Method definition
Apply
Function.apply(obj,args)The method can receive two parameters:
obj: This object will replace the This object in the function class
args: This is an array or an array of classes , and the Apply method passes the elements in the collection as arguments to the called function .
Pager
The call method is the same as the first parameter of the apply method , except that the second argument is a list of arguments
In non-strict mode when our first argument is passed to null or undefined, this in the body of the function points to the default host object, which in the browser is the window
// in non-strict mode when our first argument is passed to null or undefined, this in the body of the function points to the default host object, which in the browser is the window var function () { Console.log (this = =window);} Test.apply (null); // truetest.call (undefined); // true
Usage
1.methods of "hijacking" others (personal feelings are also inherited )
// The logname method in Foo will be referenced by bar, this points to bar var foo = { name:"mingming", logName:function() { Console.log ( this. name);} } var bar={ name:"Xiaowang"};foo.logname.call (bar); // Xiaowang
2. Implementing Inheritance
function Animal (name) { this. Name = name; This function () { Console.log (this. Name); } } function Cat (name) { Animal.call (this, name); } var New Cat ("Black cat"); // Black Cat
The usage and difference between apply and call in JS