Some key points of knowledge about JS (Call,apply,callee, Caller,clourse,prototypechain)

Source: Internet
Author: User

Maybe a lot of learning JavaScript will be confused when using Call,apply,callee, the following hope is helpful for you:

1, ~~~call, apply is a function (function object) method, Callee is the function arguments object's property reference function itself

2, ~~~call,apply Change the context object this point

3. ~~call the Apply method to let the function be called as a method of another object

4, ~ ~ The Apply method can only accept the array as a parameter

>> Call

F.call (o,1,2) is equivalent to
O.M = f;
(O.M);
Example 1:
function O1 (value) {
if (value < 100) {
This.value = value;
}else{
This.value = 100;
}
}

function O2 (value) {
O1.call (This,value); Changing the O1 function, the context object of this point
alert (this.value);
}

var o = new O2 (133554)//100 changed the point of this

Example 2:
function C1 () {
THIS.M1 = function () {
alert (this.name);
}
}

function C2 () {
THIS.name = "Mike";
}
var nc1 = new C1 ();
var nc2 = new C2 (); Have to
Nc1.m1.call (NC2); Mike refers to the method M1 as an object Nc2

>> Apply
Example 3:
function O1 (ARG) {
if (Arguments[1] < 100) {
This.value = arguments[1];
}
else {
This.value = 100;
}
}

function O2 (ARG) {
O1.apply (this, ARG);
alert (this.value);
}

var o = new O2 ([101,60])//60 parameter can only be an array

>> callee

Callee usage, commonly used in anonymous functions
var factorial = function (x) {
if (x <= 1) {
return 1;
}
return x * Arguments.callee (X-1); callback function itself
}
Alert (factorial (5)); 120


---------------------------------------------------------------------------------


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 passes the function arguments in order (starting with the second argument).
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the wording of the Apply: Func.apply (Func1,[var1,var2,var3])

~ ~ ~ With the greatest benefit of apply, you can pass in the arguments object of the current function (arguments is a pseudo-array) as the second parameter of apply.

var func=new function () {this.a= "func"}
var myfunc=function (x, y) {
var a= "MyFunc";
alert (THIS.A);
Alert (x + y);
}

Differences in parameters passed in when call and apply are called

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.

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 that is being executed
[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 recursion of an anonymous function or guarantees the encapsulation of a function, such as a recursive calculation of 1 to N of the sum of natural numbers from the bottom example. This property is available only if the related function is executing. It is also important to note that Callee has the length property, which is sometimes used for validation or better. Arguments.length is the length of the argument, and the arguments.callee.length is the length of the formal parameter, thus determining whether the parameter length is consistent with the argument length.

Callee can print its own
function Calleedemo () {
alert (Arguments.callee);
}
Calleedemo ();


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 + ", 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

var first_object = {
Num:42
};
var second_object = {
Num:24
};
function Multiply (mult) {
return this.num * mult; This is defined under global scope to point to window
}
Binds a function object to the specified object, as a method of the object, and returns the method of the object
Function.prototype.bind = function (obj) {
var method = This,
temp = function () {
return method.apply (obj, arguments);
};
return temp;
}
var first_multiply = Multiply.bind (First_object); Binds the context object and returns the anonymous function that wraps the original function
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.

~ ~ ~ Good explaintion
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 parent function executes and returns, the closure makes the garbage collection mechanism of the JavaScript GC not reclaim the resources occupied by the parent function, because the execution of the intrinsic function of the parent function depends on the variables inside it.

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.

~ ~ ~ A closure is when a function returns, a stack that does not release resources

Example 1:

<script type= "text/javascript" >
function Setupsomeglobals () {
//Local variable that ends up within Closu Re
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) "> Assignment 5-gsetnumber (5) </button >


Example 2:

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


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.


Related tips:

There is also a technique for applying call and apply, in which another function (class) is applied with call and apply, and the current
A function (class) has a method or property of another function (class), which can also be called "Inheritance". Look at the following example:

Inherited demos
function Base () {
This.member = "Dnnsun_member";
This.method = function () {
Window.alert (This.member);
}
}
function Extend () {
Base.call (this);
Window.alert (This.member);
Window.alert (This.method);
}

As can be seen from the above example, extend can inherit the methods and properties of base after call.

By the way, using apply in the JavaScript framework prototype creates a schema that defines the class.

The implementation code is as follows:

var Class = {
Create:function () {
return function () {
This.initialize.apply (this, arguments);
}
}
}
Parsing: From the code perspective, the object contains only one method: Create, which returns a function, the class. But it's also a class.
constructor, which calls initialize, which is the initialization function defined at the time the class is created. Through this way,
You can implement the class creation pattern in prototype

Example:
var vehicle=class.create ();
vehicle.prototype={
Initialize:function (type) {
This.type=type;
}
Showself:function () {
Alert ("This vehicle is" + this.type);
}
}

var moto=new vehicle ("moto");
Moto.showself ();

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.