One, call method
Call one of the object's methods and replace the current object with another object (in fact, change the object's internal pointer, that is, change the object's this point).
JS Code
Call ([thisobj[,arg1[, arg2[, [,. argn]]]]
Parameters
Thisobj
Options available. The object that will be used as the current object.
Arg1, Arg2, argn.
Options available. A sequence of method parameters is passed.
Description
The call method can be used to invoke 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 supplied, the Global object is used as a thisobj.
JS Code
Copy Code code 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 Code code 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, that is, inside the function. Subsequent arguments are parameters that are passed to the current object.
Both apply and call are the same in effect, but they differ in their parameters. The same is true for the first parameter, but for the second argument: Apply is passed an array of arguments, that is, multiple arguments are grouped into an array, and call is passed as a call parameter (starting with the second argument).
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding apply is written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3)) The advantage of using apply at the same time is that the arguments object of the current function can be passed in directly as the second argument to apply.
JS Code
Copy Code code 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 functions, the caller property is only defined 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 the string context, the result is the same as functionname.tostring, that is, the inverse compiled text of the function is displayed.
JS Code
Copy Code code as follows:
function Calllevel () {
if (Calllevel.caller = null)
Alert ("Calllevel is called from");
Else
Alert ("Calllevel is called by another function:\n" +calllevel.caller);
}
function Funcaller () {
Calllevel ();
}
Calllevel ();
Funcaller ()
Four, callee property
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 a arguments object that represents a reference to the function object itself, which facilitates hiding
The recursion of a function or the encapsulation of a function, such as the sum of the natural numbers of 1 to n in the following example. and the property
Available only if the related function is executing. Also note that callee has the length attribute, which is sometimes
For validation or better. Arguments.length is the actual parameter length, Arguments.callee.length is
The length of the formal parameter, which can be used to determine whether the parameter length of the call is consistent with the actual parameter length.
JS Code
Copy Code code 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 parameter and argument length is correct!") ");
Return
} else {
Alert ("Actual parameter length:" +arguments.length);
Alert ("Parameter length:" +arguments.callee.length);
}
}
Recursive computation
var sum = function (n) {
if (n <= 0)
return 1;
Else
return n +arguments.callee (n-1)
}
v. Bind
JS Code
Copy Code code 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)
The term "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 for the use of intrinsic functions-that is, function definitions and function expressions in functions within another function. Furthermore, these internal functions can access all the local variables, arguments, and other internal functions declared in the external function in which they are located. A closure is formed when one of these intrinsic functions is called outside the external function that contains them. That is, the internal function is executed after the external function returns. When this intrinsic function executes, it must still access the local variables, parameters, and other internal functions of its external function. These local variables, parameters, and function declarations (initially) are values that are returned by the external function, but are also affected by intrinsic functions.
In short, the function of closures is that when the out function finishes and returns, the closure makes the JavaScript garbage collection mechanism GC not reclaim the resources that the out function occupies, because the internal functions of the out function inner The execution of a function needs to depend 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 active.
2. A closure is when a function returns, a stack area without releasing resources.
Example 1:
HTML code
Copy Code code as follows:
<script type= "Text/javascript" >
function Setupsomeglobals () {
Local variable which 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 ()" > Add-gincreasenumber () </button>
<button onclick= "Gsetnumber (5)" > Assigned value 5-gsetnumber (5) </button>
Example 2:
HTML code
Copy Code code as follows:
<script type= "Text/javascript" >
function Newclosure (Somenum, Someref) {
Local variables this 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 ({somevar: ' Never-online '})
var closure2 = newclosure ({somevar: ' Bluedestiny '})
Closure1 (4)
Closure2 (3)
</script>
Example 3:
JS Code
Copy Code code as follows:
<script language= "JavaScript" >
/* Declare a global variable-getimginpositioneddivhtml-and assign it to an internal function that calls an external function expression once.
This intrinsic function returns an HTML string that surrounds an IMG element with a DIV element that represents absolute positioning, so
All mutable property values are provided by the arguments when the function is invoked:
*/
var getimginpositioneddivhtml = (function () {
/* The local variable of an external function expression-buffar-holds the buffer array. This array will only be created once, and the resulting array instance will always be available for internal functions
Therefore, it can be used each time the internal function is invoked.
The empty string is used as a data placeholder, and 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-side 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 transfer storage
' Alt=\ ',
",//index, IMG alt text content
' ><\/div> '
];
/* Returns an internal function object that is evaluated as the result of a function expression evaluation.
This intrinsic function is the function that executes every time the call is
-Getimginpositioneddivhtml (...)-
*/
Return (function (URL, id, width, height, top, left, AltText) {
/* Inserts different parameters into the appropriate location 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 by using an empty string (equivalent to connecting an array element)
A string that is formed after each element of the array is connected:
*/
Return Buffar.join (");
}); : An internal function expression ends.
}) ();//From Call
alert (getimginpositioneddivhtml);//show Returned function
Alert (getimginpositioneddivhtml ("Img.gif", "img", 100,50,0,0, "Test"));
</script>
Note: The key technique is to create an additional execution environment by executing a single line (in-line) function expression, and the intrinsic function returned by that function expression as a function to be used in external code. At this point, 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 is only created once, and can be reused by functions that depend on it.
Seven, prototype chain
ECMAScript defines an internal [[prototype]] property for the Object type. This property cannot be accessed directly from the script, but during property accessor parsing, the chain of objects referenced by this internal [[prototype]] attribute is used-that is, the prototype chain. You can assign or define a prototype object that corresponds to an internal [[prototype]] property through a public prototype property.
Example 1:
JS Code
Copy Code code as follows:
<script language= "JavaScript" >
function Numobject (formalparameter) {
This.testnumber = FormalParameter;
}
function Strobject (formalparameter) {
this.teststring = FormalParameter;
}
Replaces all prototypes associated with an instance 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.
When you read a named property value in the object or object's prototype, only the property value found first is returned. When you assign a value to a named property of an object, the property is created if the object itself does not exist.
alert (objref.teststring);//output "String_value"
alert (objref.testnumber);//output "6"
alert (objref.tostring);
The Strobject instance has a prototype chain. The first object in the chain is an instance of the Numobject that was assigned to the prototype property of the Strobject constructor after it was created. An instance of Numobject also has a prototype, which is the prototype of the default object object that corresponds to the object 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);//itself has attributes, the property accessor will not further search the prototype chain
Alert (NumObject.prototype.isPrototypeOf (OBJREF));//Output "true"
</script>
0 0 0