JS experience bit JS Apply/call/caller/callee/bind using method and Difference analysis

Source: Internet
Author: User

First, call method
Invokes one method of an object, replacing the current object with another object (in fact, changing the object's internal pointer, which changes the contents of the object's this point).
JS Code
Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Parameters
Thisobj
Options are available. The object that will be used as the current object.
Arg1, Arg2,, ArgN
Options are available. The method parameter sequence will be passed.
Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj. If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
JS Code

Copy CodeThe code is as follows:
<input type= "text" id= "MyText" value= "input text" > Code
function Obj () {this.value= "Object! ";}
var value= "global variable";
function Fun1 () {alert (this.value);}
Window. Fun1 (); Global variables
Fun1.call (window); Global variables
Fun1.call (document.getElementById (' MyText ')); Input text
Fun1.call (New OBJ ()); Object!


JS Code
Code

Copy CodeThe 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


Second, apply method
The first parameter of the Apply method is also the object to pass to the current object, which is the this within the function. The arguments that follow are all arguments passed to the current object.
Both apply and call are the same in effect, but they differ in parameters. For the first parameter, the meaning is the same, but for the second argument: Apply passes in an array of parameters, which is the combination of multiple parameters into an array, and call is passed in as a parameter of call (starting with the second argument).
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the wording of apply: Func.apply (func1, [VAR1,VAR2,VAR3]) The benefit of using apply at the same time is that you can directly pass in the arguments object of the current function as the second parameter of apply.
JS Code

Copy CodeThe 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"


Third, caller properties
Returns a reference to a function that invokes the function body of the current function.
The FunctionName.caller:functionName object is the name of the function being executed.
Description
For a function, the caller property is defined only when the function executes. If the function is called by the top level of a JScript program, then caller contains null. If you use the Caller property in a string context, the result is the same as functionname.tostring, that is, the deserialized text of the function is displayed.
JS Code

Copy CodeThe code is as follows:
function Calllevel () {
if (Calllevel.caller = = null)
Alert ("Calllevel is called from the top level.");
Else
Alert ("Calllevel is called by another function:\n" +calllevel.caller);
}
function Funcaller () {
Calllevel ();
}
Calllevel ();
Funcaller ()


Iv.. callee Properties
Returns the function object being executed, which is the body of the specified function object.
[function.] Arguments.callee: The optional function parameter is the name of the function object that is currently executing.
Description
The initial value of the Callee property is the Function object that is being executed.
The Callee property is a member of the arguments object that represents a reference to the function object itself, which facilitates the hiding
recursive function or guarantee the encapsulation of functions, such as the following example of the recursive calculation of 1 to n the sum of natural numbers. And this property
Available only if the related function is executing. It is also important to note that Callee has the length property, which is sometimes
For validation or better. Arguments.length is the argument length, Arguments.callee.length is
Parameter length, which can be used to determine if the parameter length is the same as the argument length at the time of the call.
JS Code

Copy CodeThe code is as follows:
Callee can print its own
function Calleedemo () {
alert (Arguments.callee);
}
Used to validate parameters
function Calleelengthdemo (arg1, arg2) {
if (arguments.length==arguments.callee.length) {
Window.alert ("Verify that the parameters and argument lengths are correct!") ");
Return
} else {
Alert ("Argument 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)
}


Five, bind
JS Code

Copy CodeThe 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


Six, JS closure (Closure)
A "closure" refers to an expression (usually a function) that has many variables and an environment that binds them, and therefore these variables are also part of the expression.
The simplest description of closures is that ECMAScript allows the use of intrinsic functions-that is, function definitions and function expressions in the function body of another function. Furthermore, these intrinsic functions can access all local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed. That is, the intrinsic function is executed after the external function returns. When this inner function executes, it still has to access local variables, arguments, and other intrinsic functions of its external function. The values of these local variables, parameters, and function declarations (initially) are the values that are returned by the external function, but are also affected by intrinsic functions.
In short, the function of a closure is that after the out function is executed and returned, the closure makes the garbage collection mechanism of the JavaScript GC not reclaim the resources occupied by the out function, because the internal function of the out functions inner The execution of a function depends on the variables in the Out function.
Two features of closures:
1, as a reference to a function variable-when the function returns, it is in the active state.
2, a closure is when a function returns, a stack that does not release resources.
Example 1:
HTML code

Copy CodeThe 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;}
}
</script>
<button onclick= "setupsomeglobals ()" > Build-setupsomeglobals () </button>
<button onclick= "Galertnumber ()" > Output value-galertnumber () </button>
<button onclick= "Gincreasenumber ()" > Increase-gincreasenumber () </button>
<button onclick= "Gsetnumber (5)" > Assignment 5-gsetnumber (5) </button>


Example 2:
HTML code

Copy CodeThe code is as follows:
<script type= "Text/javascript" >
function Newclosure (Somenum, Someref) {
Local variables that end up within closure
var num = somenum;
var = [Anarray];
var ref = Someref;
return function (x) {
num + = x;
Anarray.push (num);
Alert (' num: ' + num +
' Nanarray ' + anarray.tostring () +
' Nref.somevar ' + Ref.somevar);
}
}
var closure1 = Newclosure (+, {somevar: ' Never-online '})
var = newclosure (Closure2, {somevar: ' Bluedestiny '})
Closure1 (4)
Closure2 (3)
</script>


Example 3:
JS Code

Copy CodeThe code is as follows:
<script language= "JavaScript" >
/* Declare a global variable-getimginpositioneddivhtml-and assign it a call to an internal function that returns an external function expression.
This intrinsic function returns an HTML string that represents an IMG element surrounded by an absolute positioning DIV element, so that
All mutable property values are provided by the parameters when the function is called:
*/
var getimginpositioneddivhtml = (function () {
/* local variable of the external function expression-buffar-holds the buffer array. This array is created only once, and the resulting array instance is always available to the intrinsic function
Therefore, it can be used every time this intrinsic function is called.
Where the empty string is used as a placeholder for data, the corresponding data
will be inserted into this array by an intrinsic function:
*/
var Buffar = [
' <div id= ',
",//index 1, DIV ID attribute
' "style=" position:absolute;top: ',
",//index 3, DIV top position
' Px;left: ',
",//index 5, DIV left end position
' Px;width: ',
",//index 7, DIV width
' Px;height: ',
",//index 9, DIV height
' Px;overflow:hidden;\ ' ><img src=\ "',
",//index, IMG URL
' \ ' width=\ ',
",//index, IMG width
' \ ' height=\ ',
",//index, IMG storage
' \ ' alt=\ ',
",//index, IMG alt text content
' \ ' ><\/div> '
];
/* Returns an intrinsic function object as the result of evaluating the function expression.
This intrinsic function is the function that executes each call
-Getimginpositioneddivhtml (...)-
*/
Return (function (URL, id, width, height, top, left, AltText) {
/* Insert different parameters into the buffer array in the appropriate location:
*/
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 by using an empty string (equivalent to connecting an array element)
A string formed after each element of the array is concatenated:
*/
Return Buffar.join (");
}); : An inner function expression ends.
});//self-invocation
alert (getimginpositioneddivhtml);//Displays the returned function
Alert (getimginpositioneddivhtml ("Img.gif", "img", 100,50,0,0, "Test"));
</script>


Description: One of the key techniques is to create an additional execution environment by executing a single-line (in-line) function expression, and the intrinsic function returned by the function expression as a function for use in external code. At this point, the buffered array is defined as a local variable of the function expression. This function expression is executed only once, and the array is created once and can be reused for functions that depend on it.
Seven, the prototype chain
ECMAScript defines an internal [[prototype]] property for the Object type. This property cannot be accessed directly through a script, but during property accessor parsing, you need to use the chain of objects referenced by this internal [[prototype]] Property-that is, the prototype chain. A common prototype property can be used to assign or define a prototype object corresponding to an internal [[prototype]] property.
Example 1:
JS Code

Copy CodeThe code is as follows:


<script language= "JavaScript" >
function Numobject (formalparameter) {
This.testnumber = FormalParameter;
}
function Strobject (formalparameter) {
this.teststring = FormalParameter;
}
Replaces all prototypes associated with instances of the Strobject class with an instance of the Numobject class.
Strobject.prototype =new Numobject (6);
var objRef = new Strobject ("String_value");
When a property accessor attempts to read the property value of an object referenced by ObjectRef, the entire prototype chain is searched.
In the prototype of an object or object, only the value of the property that was found first is returned when the named property value is read. When you assign a value to a named property of an object, the property is created if the object does not exist on its own.
alert (objref.teststring);//output "String_value"
alert (objref.testnumber);//output "6"
alert (objref.tostring);
An instance of Strobject has a prototype chain. The first object in the chain is an instance of Numobject that is assigned to the prototype property of the Strobject constructor after it is created. An instance of Numobject also has a prototype, a prototype of the default object object corresponding to the objects referenced by Object.prototype. Finally, Object.prototype has a prototype with a value of NULL, so this prototype chain ends here.
Objref.testnumber = 3;//object itself does not exist this property creates the corresponding property
alert (objref.testnumber);//property accessor no longer searches the prototype chain
Alert (NumObject.prototype.isPrototypeOf (OBJREF));//Output "true"
</script>

JS experience bit JS Apply/call/caller/callee/bind using method and Difference analysis

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.