call() and
apply() are predefined
JavaScript function methods. Both methods can be used to invoke a function, and
both methods must have the owner object as first parameter.
function myFunction(a, b) {
return a * b;
}
myObject = myFunction.call(myObject, 10, 2); // Will return 20
function myFunction(a, b) {
return a * b;
}
myArray = [10, 2];
myObject =
myFunction.apply(myObject, myArray); // Will also return 20
The
only difference is that
call() takes the function arguments separately, and
apply() takes the function arguments in an array.
In JavaScript strict mode, the first argument becomes the value of
this in
the invoked function, even if the argument is not an object.
In "non-strict" mode, if the value of the first argument is null or undefined, it
is replaced with the global object.
With call() or apply() you can set the value of this,
and invoke a function as a new method of an existing object.
http://www.w3schools.com/js/js_function_invocation.asp
No comments:
Post a Comment