Js apply/call/caller/callee/bind usage and Difference Analysis

Source: Internet
Author: User
Tags define prototype

Js apply/call/caller/callee/bind usage and Difference Analysis
I. call Method
Call a method of an object to replace the current object with another object (in fact, it is to change the internal pointer of the object, that is, to change the content pointed to by this object ).
Js Code
Call ([thisObj [, arg1 [, arg2 [, [,. argN])
Parameters
ThisObj
Optional. Will be used as the object of the current object.
Arg1, arg2, and argN
Optional. The method parameter sequence will be passed.
Description
The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj. If the thisObj parameter is not provided, the Global object is used as thisObj.
Js Code
The Code is as follows:
Code
Function Obj () {this. value = Object !;}
Var value = global variable;
Function Fun1 () {alert (this. value );}
Window. Fun1 (); // global variable
Fun1.call (window); // global variable
Fun1.call (document. getElementById ('mytext'); // input text
Fun1.call (new Obj (); // object!

Js Code
Code
The Code is as follows:
Var first_object = {
Num: 42
};
Var second_object = {
Num: 24
};
Function multiply (mult ){
Return this. num * mult;
}
Multiply. call (first_object, 5); // returns 42*5
Multiply. call (second_object, 5); // returns 24*5

Ii. apply Method
The first parameter of the apply method is the object to be passed into the current object, that is, this in the function. The following parameters are the parameters passed to the current object.
The apply and call functions are the same, but they have different parameters. The meaning of the first parameter is the same, but for the second parameter: apply is a parameter array, that is, multiple parameters are combined into an array and passed in, call is passed in as the call parameter (starting with the second parameter ).
For example, func. the apply method for call (func1, var1, var2, var3) is: func. the benefit of applying (func1, [var1, var2, var3]) is that the arguments object of the current function can be directly passed as the second parameter of apply.
Js Code
The Code is as follows:
Var func = new function () {this. a = func}
Var myfunc = function (x, y ){
Var a = myfunc;
Alert (this. );
Alert (x + y );
}
Myfunc. call (func, var, fun); // func var fun
Myfunc. apply (func, [var, fun]); // func var fun

Iii. caller attributes
Returns a reference to the function, that is, the function body that calls the current function.
FunctionName. caller: the name of the function to be executed.
Note:
For a function, the caller attribute is defined only when the function is executed. If the function is called by the top layer of the JScript program, caller contains null. If the caller attribute is used in the string context, the result is the same as functionName. toString, that is, the decompilation Text of the function is displayed.
Js Code
The Code is as follows:
Function CallLevel (){
If (CallLevel. caller = null)
Alert (CallLevel was called from the top level .);
Else
Alert (CallLevel was called by another function: + CallLevel. caller );
}
Function funCaller (){
CallLevel ();
}
CallLevel ();
FunCaller ()

Iv. callee attributes
Returns the Function object being executed, that is, the body of the specified Function object.
[Function.] arguments. callee: the name of the currently executed function object.
Note:
The initial value of the callee attribute is the Function object being executed.
The callee attribute is a member of the arguments object. It indicates a reference to the function object.
Recursion of a function or encapsulation of a function. For example, the following example recursively calculates the sum of natural numbers from 1 to n. This attribute
It is available only when the related function is being executed. Note that callee has the length attribute, which is sometimes
It is better for verification. Arguments. length is the length of the real parameter, and arguments. callee. length is
The length of the parameter to determine whether the length of the parameter is consistent with that of the actual parameter.
Js Code
The Code is as follows:
// Callee can print itself
Function calleeDemo (){
Alert (arguments. callee );
}
// Used to verify Parameters
Function calleeLengthDemo (arg1, arg2 ){
If (arguments. length = arguments. callee. length ){
Window. alert (verify that the length of the form parameter and real parameter is correct !);
Return;
} Else {
Alert (real parameter length: + arguments. length );
Alert (parameter length: + arguments. callee. length );
}
}
// Recursive Calculation
Var sum = function (n ){
If (n <= 0)
Return 1;
Else
Return n + arguments. callee (n-1)
}

V. bind
Js Code
The Code is as follows:
Var first_object = {
Num: 42
};
Var second_object = {
Num: 24
};
Function multiply (mult ){
Return this. num * mult;
}
Function. prototype. bind = function (obj ){
Var method = this,
Temp = function (){
Return method. apply (obj, arguments );
};
Return temp;
}
Var first_multiply = multiply. bind (first_object );
First_multiply (5); // returns 42*5
Var second_multiply = multiply. bind (second_object );
Second_multiply (5); // returns 24*5

Vi. JS Closure (Closure)
A closure refers to an expression (usually a function) with many variables and an environment bound to these variables. Therefore, these variables are part of the expression.
The simplest description of closures is that ECMAScript allows internal functions-that is, function definitions and function expressions are located in the body of another function. In addition, these internal functions can access all the local variables, parameters, and other declared internal functions declared in their external functions. When one of these internal functions is called outside the external functions that contain them, a closure is formed. That is to say, the internal function will be executed after the external function returns. When this internal function is executed, it must still access the local variables, parameters, and other internal functions of its external function. The values of these local variables, parameters, and function declarations (initially) are the values returned by external functions, but they are also affected by internal functions.
In short, the function of the closure is that after the out function is executed and returned, the closure makes the garbage collection mechanism of Javascript GC not to reclaim the resources occupied by the out function, because the execution of the inner function of the out function depends on the variables in the out function.
Closure has two features:
1. As a reference to a function variable-when a function is returned, it is activated.
2. A closure is a stack that does not release resources when a function returns.
Example 1:
Html code
The Code is as follows:
<Script type = text/javascript>
Function setupSomeGlobals (){
// Local variable that ends up within closure
Var num = 666;
// Store some references to functions as global variables
Required tnumber = function () {alert (num );}
GIncreaseNumber = function () {num ++ ;}
GSetNumber = function (x) {num = x ;}
}
</Script>
Generate-setupSomeGlobals ()
Output Value-effectnumber ()
Add-gIncreaseNumber ()
Value 5-gSetNumber (5)

Example 2:
Html code
The Code is as follows:
<Script type = text/javascript>
Function newClosure (someNum, someRef ){
// Local variables that end up within closure
Var num = someNum;
Var anArray = [1, 2, 3];
Var ref = someRef;
Return function (x ){
Num + = x;
AnArray. push (num );
Alert ('num: '+ num +
'Nanarray' + anArray. toString () +
'Nref. someVar '+ ref. someVar );
}
}
Var closure1 = newClosure (40, {someVar: 'Never-online '})
Var closure2 = newClosure (99, {someVar: 'bluedestiny '})
Closure1 (4)
Closure2 (3)
</Script>

Example 3:
Js Code
The Code is as follows:
<Script language = javascript>
/* Declare a global variable-getImgInPositionedDivHtml-and assign the internal function returned by calling an external function expression at a time.
This internal function returns an HTML string containing an IMG element, which indicates absolute positioning,
All variable attribute values are provided by the parameters when the function is called:
*/
Var getImgInPositionedDivHtml = (function (){
/* The local variable of the external function expression-buffAr-stores the buffer array. This array is created only once. The generated array instance is always available for internal functions.
Therefore, this function can be used every time you call this internal function.
The Null String is used as a data placeholder and the corresponding data
Insert the internal function into this array:
*/
Var buffAr = [
''', // Index 1, div id attribute
'Style = position: absolute; top: 'http: // www.2cto.com/kf/201508 /,
'', // Index 3, top position of the DIV
'Px; left: 'http: // www.2cto.com/kf/201508 /,
'', // Index 5, left side of the DIV
'Px; width: 'http: // www.2cto.com/kf/201508 /,
'', // Index 7, DIV width
'Px; height: 'http: // www.2cto.com/kf/201508 /,
'', // Index 9, DIV height
'Px; overflow: hidden;> '', // index 11, IMG URL
'Width = 'HTTP: // www.2cto.com/kf/201508 /,
'', // Index 13, IMG width
'Height = 'HTTP: // www.2cto.com/kf/201508 /,
'', // Index 15, IMG Storage
'Alt = "http://www.2cto.com/kf/201508,
"', // Index 17, IMG alt text content
'>'
];
/* Return the internal function object that is used as the result after the function expression is evaluated.
This internal function is the function that is called each time.
-GetImgInPositionedDivHtml (...)-
*/
Return (function (url, id, width, height, top, left, altText ){
/* Insert different parameters to the corresponding position of the buffer array:
*/
BuffAr [1] = id;
BuffAr [3] = top;
BuffAr [5] = left;
BuffAr [13] = (buffAr [7] = width );
BuffAr [15] = (buffAr [9] = height );
BuffAr [11] = url;
BuffAr [17] = altText;
/* Returns the result of concatenating array elements by using an empty string)
Concatenates each element of the array to form a string:
*/
Return buffAr. join ('');
}); //: The internal function expression ends.
}) (); // Self-called
Alert (getImgInPositionedDivHtml); // display the returned Function
Alert(getImgInPositionedDivHtml(img.gif, img, 50, Test ));
</Script>

Note: The key technique is to create an additional execution environment by executing an in-line function expression, the internal functions returned by this function expression are used in external code. In this case, the buffer array is defined as a local variable of the function expression. This function expression only needs to be executed once, And the array only needs to be created once, which can be reused by functions dependent on it.
VII. prototype chain
ECMAScript defines an internal [[prototype] attribute for the Object type. This attribute cannot be directly accessed through scripts, but the object chain referenced by this internal [prototype] attribute is required during the property accessors parsing process-the prototype chain. A common prototype attribute can be used to assign values or define prototype objects corresponding to the internal [[prototype] attribute.
Example 1:
Js Code
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.