Each function contains two non-inherited methods: Apply () and call (). The purpose of both methods is to invoke the function in a specific scope, which is actually equivalent to setting the value of the This object in the function body.
Apply ():
The method accepts two parameters: one is the scope in which the function is run, and the other is the parameter array . Where the second argument can be an instance of an Array , or it can be an arguments object. For example:
function sum (NUM1, num2) { return num1 + num2;} function CallSum1 (NUM1, num2) { return sum.apply ( Span style= "COLOR: #0000ff" >this , arguments); // incoming arguments object " function CallSum2 (NUM1, num2) { return sum.apply ( This , [num1,num2]); // incoming array }alert (CALLSUM1 ( ten, 10));
In the example above,callSum1 () passed the this value when executing the sum () function ( because it was called in the global scope, so the incoming Window object) and the arguments object.
Call ():
The call () method works the same as the Apply () method, and they differ only in the parameters that are accepted. For the call () method, the first parameter is the this value does not change, changing the rest of the parameters are passed directly to the function. In other words, when using the call () method, the arguments passed to the function must be listed individually , as shown in the following example.
function sum (NUM1, num2) { return num1 + num2;} function callsum (NUM1, num2) { return sum.call (This, NUM1, num2);} Alert (Callsum (10, 10));
In fact, passing parameters is not the real place for apply () and call (), and their real strength is the ability to expand the scope in which the function works . Let's look at an example below.
Window.color = ' red '; var o = { ' blue '}; function Saycolor () { alert (this//Bluesaycolor.call ////Blue//Red
When you run Saycolor.call (o), the execution environment of the function is different, because the this object in the function body points to O and then calls it by O.
Explanation of call () and apply (116 pages) in JavaScript advanced programming