Home  >  Article  >  Web Front-end  >  js apply/call/caller/callee/bind usage and difference analysis_javascript skills

js apply/call/caller/callee/bind usage and difference analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:43:121099browse
1. call method
Call a method of an object to replace the current object with another object (actually changing the internal pointer of the object, that is, changing the content pointed to by this of the object).
Js code
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Parameters
thisObj
Optional. The object that will be used as the current object.
arg1, arg2, , argN
Optional. A sequence of method parameters will be passed.
Description
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj. If no thisObj parameter is provided, the Global object is used as thisObj.
Js code
Copy 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
Copy 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

2. Apply method
The first parameter of the apply method is also the object to be passed to the current object, that is, this inside the function. The following parameters are the parameters passed to the current object.
Apply and call have the same function, but there are differences in parameters. The meaning of the first parameter is the same, but for the second parameter: apply passes in a parameter array, that is, multiple parameters are combined into an array and passed in, while call is passed in as the parameter of call (from the starting with two parameters).
For example, the corresponding apply writing method of func.call(func1,var1,var2,var3) is: func.apply(func1,[var1,var2,var3]). The advantage of using apply at the same time is that you can directly add the arguments object of the current function. Passed in as the second parameter of apply.
Js code
Copy code The code is as follows:

var func=new function() {this.a="func"}
var myfunc=function(x,y){
var a="myfunc";
alert(this.a);
alert(x y);
}
myfunc.call(func,"var"," fun");// "func" "var fun"
myfunc.apply(func,["var"," fun"]) ;// "func" "var fun"

3. The caller attribute
returns a reference to the function, which is the function body that calls the current function.
functionName.caller: The functionName object is the name of the function being executed.
Note:
For functions, the caller attribute is only defined when the function is executed. If the function is called from the top level of a JScript program, then caller contains null . If the caller attribute is used in a string context, the result is the same as functionName.toString, that is, the decompiled text of the function is displayed.
Js code
Copy 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:n" CallLevel.caller) ;
}
function funCaller(){
CallLevel();
}
CallLevel();
funCaller()

4. callee attribute
Returns the Function object being executed, which is the body of the specified Function object.
[function.]arguments.callee: Optional function parameter is the name of the Function object currently being executed.
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 represents a reference to the function object itself. This is helpful for hiding the recursion of the
function or ensuring the encapsulation of the function. For example, the following example recursively calculates the natural numbers from 1 to n. and. And this attribute
is only available when the related function is executing. It should also be noted that callee has a length attribute, which is sometimes
used for verification. arguments.length is the actual parameter length, and arguments.callee.length is the
formal parameter length. From this, you can determine whether the formal parameter length is consistent with the actual parameter length when calling.
Js code
Copy 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 formal and actual parameter lengths are correct!");
return;
} else {
alert("The actual parameter length: " arguments.length);
alert("Formal parameter length: " arguments.callee.length);
}
}
//Recursive calculation
var sum = function(n){
if (n <= 0)
return 1;
else
return n +arguments.callee(n - 1)
}

5. bind
Js code
Copy 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

6. JS closure (Closure)
The so-called "closure", Refers to an expression (usually a function) that has a number of variables and an environment to which these variables are bound, so that these variables are part of the expression.
Regarding closures, the simplest description is that ECMAScript allows the use of inner functions - that is, the function definition and function expression are located in the function body of another function. Furthermore, these inner functions have access to all local variables, parameters, and other inner functions declared in the outer function in which they exist. A closure is formed when one of these inner functions is called outside the outer function that contains them. That is, the inner function will be executed after the outer function returns. When this inner function is executed, it still must access the local variables, parameters and other inner functions of its outer function. The values ​​of these local variables, parameters, and function declarations (initially) are the values ​​when the outer function returns, but are also affected by the inner function.
In short, the function of the closure is that after the out function is executed and returned, the closure prevents Javascript's garbage collection mechanism GC from reclaiming the resources occupied by the out function, because the inner function of the out function's inner function Execution depends on the variables in the out function.
Two characteristics of closures:
1. As a reference to a function variable - it is activated when the function returns.
2. A closure is a stack area that does not release resources when a function returns.
Example 1:
Html code
Copy 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
gAlertNumber = function() { alert(num); }
gIncreaseNumber = function() { num ; }
gSetNumber = function(x) { num = x; }
}






Example 2:
Html code
Copy 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)


Example 3:
Js code
Copy code The code is as follows:



Explanation: The key trick is to create an additional execution environment by executing an in-line function expression. Instead, use the internal function returned by the function expression as the function used in external code. At this time, the buffer array is defined as a local variable of the function expression. The function expression only needs to be executed once, and the array is created once and can be reused by functions that depend on it.
7. Prototype chain
ECMAScript defines an internal [[prototype]] attribute for the Object type. This property cannot be accessed directly through scripts, but during the parsing process of the property accessor, the object chain referenced by this internal [[prototype]] property - the prototype chain - is needed. The prototype object corresponding to the internal [[prototype]] property can be assigned or defined through a public prototype property.
Example 1:
Js code
Copy code The code is as follows:



0 0 0
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn