Example and understanding of arguments, caller, callee, call, and apply in javascript

Source: Internet
Author: User

Before talking about the above concepts, we should first talk about the implicit parameter of the function in javascript: arguments
Arguments
This object represents the function being executed and the parameters of the function that calls it.

[Function.] arguments [n]
Parameter function: option. Name of the Function object currently being executed. N: option. The index of the parameter value starting from 0 to be passed to the Function object.
Description

Arguments is a hidden object created in addition to the specified parameters when calling a function. Arguments is an object similar to an array but not an array. It is similar to an array because it has the same access nature and method as an array, you can use arguments [n] to access the values of a single parameter and have the length attribute of the array length. In addition, the arguments object stores the parameters actually passed to the function, not limited to the list of parameters defined in the function declaration, and cannot explicitly create the arguments object. The arguments object is available only when the function starts. The following example details these properties:
Copy codeThe Code is as follows:
// Usage of the arguments object.
Function ArgTest (a, B ){
Var I, s = "The ArgTest function expected ";
Var numargs = arguments. length; // obtain the value of the passed parameter.
Var expargs = ArgTest. length; // obtain the value of the expected parameter.
If (expargs <2)
S + = expargs + "argument .";
Else
S + = expargs + "arguments .";
If (numargs <2)
S + = numargs + "was passed .";
Else
S + = numargs + "were passed .";
S + = "\ n"
For (I = 0; I <numargs; I ++) {// obtain the parameter content.
S + = "Arg" + I + "=" + arguments [I] + "\ n ";
}
Return (s); // return the parameter list.
}

A code indicating that arguments is not an Array (Array class) is added here:

Copy codeThe Code is as follows:
Array. prototype. selfvalue = 1;
Alert (new Array (). selfvalue );
Function testAguments (){
Alert (arguments. selfvalue );
}

Run the code and you will find that the first alert shows 1, which indicates that the array object has the selfvalue attribute and the value is 1. When you call the testAguments function, "undefined" is displayed, indicating that it is not an attribute of arguments, that is, arguments is not an array object.
The following is a simple method recommended for attaching:
Copy codeThe Code is as follows:
Alert (arguments instanceof Array );
Alert (arguments instanceof Object );


Caller
Returns a reference to the function that calls the current function.
FunctionName. caller
The functionName object is the name of the executed function.
Description
For a function, the caller attribute is defined only when the function is executed. If the function is called by the top layer, 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.
The following example illustrates the usage of caller attributes:
Copy codeThe Code is as follows:
// Caller demo {
Function callerDemo (){
If (callerDemo. caller ){
Var a = callerDemo. caller. toString ();
Alert ();
} Else {
Alert ("this is a top function ");
}
}
Function handleCaller (){
CallerDemo ();
}

Callee

Returns the Function object being executed, that is, the body of the specified Function object.

[Function.] arguments. callee
The optional function parameter is the name of the currently executed Function object.

Description

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 itself, which facilitates anonymity.
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.

Example

Copy codeThe 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)
}

Typical recursive functions:
Copy codeThe Code is as follows:
Var sum = function (n ){
If (1 = n) return 1;
Else return n + sum (n-1 );

Call time: alert (sum (100 ));
The function contains a reference to sum itself. The function name is only a variable name. Calling sum inside the function is equivalent to calling
A global variable cannot reflect the call itself. Using callee is a good method.

Apply and call

They are used to bind a function to another object for running. The two are different only when defining parameters:

Apply (thisArg, argArray );

Call (thisArg [, arg1, arg2…] ]);

That is, the this pointer inside all functions will be assigned to thisArg, which can be used to run functions as methods of another object.

Description of apply

If argArray is not a valid array or an arguments object, a TypeError occurs.
If neither argArray nor thisArg is provided, the Global object will be used as thisArg,
And no parameters can be passed.

Call description

The call method can change the object context of a function from the initial context to the new object specified by thisArg.
If the thisArg parameter is not provided, the Global object is used as the thisArg

Related skills:

There is another technique in applying call and apply, that is, after applying call and apply to another function (class), the current
A function (class) has another function (class) method or attribute, which can also be called "inheritance ". See the following example:
Copy codeThe Code is as follows:
// Inherited demo
Function base (){
This. member = "dnnsun_Member ";
This. method = function (){
Window. alert (this. member );
}
}
Function extend (){
Base. call (this );
Window. alert (member );
Window. alert (this. method );
}

The example above shows that after calling, extend can inherit the methods and attributes of the base.

By the way, use apply in the prototype of the javascript framework to create a schema that defines classes,

The implementation code is as follows:
Copy codeThe Code is as follows:
Var Class = {
Create: function (){
Return function (){
This. initialize. apply (this, arguments );
}
}
}

Resolution: From the code, this object only contains one method: Create, which returns a function, that is, a class. But this is also a class
The constructor calls initialize, which is the initialization function defined during class creation. In this way,
The class Creation Mode in prototype can be implemented.

Example:
Copy codeThe Code is as follows:
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 ();


For more details about prototype, go to its official website.

The comments also have a better understanding of this. I will not add any more here. Let's take a look at it for better understanding.
After reading the above code, you can see the following code for those who want to see the effect immediately. Multiple tests.
Copy codeThe Code is as follows:
<Script language = "JavaScript">
/**//*
* Demonstrate the usage of arguments and how to obtain real parameters and number of shapes
*/
Function argTest (a, B, c, d ){
Var numargs = arguments. length; // obtain the value of the passed parameter.
Var expargs = argTest. length; // obtain the value of the expected parameter.
Alert ("the number of real parameters is:" + numargs)
Alert ("the number of shapes is:" + expargs)

Alert (arguments [0])
Alert (argTest [0]) // undefined does not have this usage
}
// ArgTest (1, 2)
// Result: the number of real parameters is 2. The number of parameters is 4. 1. undefined.
// ArgTest (1, 2, 3, 4, 5)
// Result: the number of real parameters is 5, the number of parameters is 4, 1, and undefined.
/* Conclusion: js parameter passing does not require the same syntax as c # And function definition. parameters can be added or removed based on different applications. In extreme cases, parameters can be not declared, for example */
Var test = function (){
Var a = 0;
Var l = 0;
While (l <arguments. length)
{
A + = arguments [l];
L ++;
}
Alert ();
}
Test (); // 0
Test (1, 2); // 3

/**//*
* Arguments is not an Array (Array class)
*/

Array. prototype. selfvalue = 1;
// This is an object that is criticized for rendering the original sound.
Function testAguments (){
Alert ("arguments. selfvalue =" + arguments. selfvalue );
}
// Alert ("Array. sefvalue =" + new Array (). selfvalue );
/* The above call indicates that the selfvalue of all Array objects is equal to 1 */
// TestAguments ();
/* The undefined result indicates that arguments is not of the Array type */

/**//*
* Demonstrate the caller attribute of the function.
* Description: (current function). caller: returns a reference to the function, which calls the current function.
*/

Function callerDemo (){
If (callerDemo. caller ){
Var a = callerDemo. caller. arguments [0];
Alert ();
} Else {
Alert ("this is a top function ");
}
}
Function handleCaller (){
CallerDemo ();
}

// CallerDemo ();
// Result: this is a top function
// HandleCaller ("parameter 1", "parameter 2 ");
// Result: parameter 1
/* Conclusion: caller applies to function objects and can obtain the function objects and parameters called at the upper layer.
*/

/**//*
* Shows the callee attribute of the function.
* Description: arguments. callee: the initial value is the Function object being executed. It is used for anonymous functions.
*/
Function calleeDemo (){
Alert (arguments. callee );
}
// CalleeDemo ();
// (Function (arg0, arg1) {alert ("Quantity:" + arguments. callee. length )})();
/* Conclusion: it can be used to implement recursion, for example :*/
Var I = 0;
Var a = function (){
I + = arguments [0];
If (I> 100 | I = 0)
Alert (I );
Else
Arguments. callee (I );
};
A (1 );
// Result 128 is actually the 7th Power of 2


/**//*
* Demonstrate the usage of the apply and call Functions
* Note: The function is used to bind a function to another object for running. The two functions are different only when defining parameters:
* Apply (thisArg, argArray );
* Call (thisArg [, arg1, arg2…] ]);
* That is, the this pointer inside all functions will be assigned to thisArg.
*/

Function ObjectA (){
Alert ("execute ObjectA ()");
Alert (arguments [0]);
This. hit = function (msg) {alert (msg )}
This.info = "I'm from ObjectA"
}

Function ObjectB (){
Alert ("execute ObjectB ()");
// Call the ObjectA () method, and all this in the ObjectA constructor will be replaced by this in ObjectB.
ObjectA. apply (this, arguments); // ObjectA. call (this );
Alert (this.info );
}
// ObjectB ('parameter 0 ');
/* Conclusion: usually used with callee */
Var I = 0
Function a (B)
{
I ++;
If (I> 4)
Return I;
Else
Return arguments. callee. call (this, B );
}
Alert (a (0 ));

// Describes the scope of this.

Var value = "global variable ";
Function Obj (){
This. value = "object! ";
}
Function Fun1 (){
Alert (this. value );
}
// Fun1 ();
// Result: global variable
// Fun1.apply (window );
// Result: global variable. The default value is this = window.
// Fun1.apply (new Obj ());
// Result: object. this = new Obj (); this in Obj indicates the function object instance.
</Script>

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.