call () and apply ()

In JavaScript, functions are objects. JavaScript function has its attributes and methods.

call ()  and  apply ()  is a function of a predefined method. Two methods can invoke the function, the first two parameters of the method must be an object itself.

function myFunction(a, b) {
    return a * b;
}
myObject = myFunction.call(myObject, 10, 2);     // 返回 20
function myFunction(a, b) {
    return a * b;
}
myArray = [10, 2];
myObject = myFunction.apply(myObject, myArray);  // 返回 20

Both methods use the object itself as the first parameter.

The difference is that the second argument: apply a parameter is passed the array, i.e. the array into a plurality of combinations of parameters passed, and the call is an incoming call as a parameter (second parameter starts).

In JavaScript strict mode (strict mode), when you call the first argument will be  this  value, even if the parameter is not an object.

In JavaScript non-strict model (non-strict mode), if the value of the first parameter is null or undefined, it uses the global object instead.

Guess you like

Origin www.cnblogs.com/pfeiliu/p/12071097.html
Recommended