JavaScript arguments,caller,callee,call,apply Examples and understanding _javascript skills

Source: Internet
Author: User
Tags function definition inheritance numeric value
Before you mention the above concepts, first of all, let's talk about the implied parameters of functions in javascript: arguments
Arguments
The object represents the function being executed and the arguments of the function that called it.

[function.] Arguments[n]
Parameter function: option. The name of the Function object that is currently executing. N: Options. The 0-based parameter value index to pass to the Function object.
Description

Arguments is a hidden object that is created in addition to the specified parameters when a function call is made. Arguments is an array-like but not an array object, saying that it is similar to an array because it has the same access property and manner as an array, and can be accessed by arguments[n] to the value of the corresponding individual parameter and to have the length of the array. And the arguments object stores the arguments that are actually passed to the function, not the list of parameters defined by the function declaration, and the arguments object cannot be explicitly created. The arguments object is available only when the function starts. The following examples illustrate these properties in detail:
Copy Code code as follows:

The use of arguments objects.
function Argtest (A, b) {
var i, S = "The Argtest function expected";
var Numargs = arguments.length; Gets the numeric value of the parameter being passed.
var Expargs = argtest.length; Gets the numeric 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++) {//Get parameter content.
S + + "ARG" + i + "=" + arguments[i] + "\ n";
}
return (s); Returns a list of parameters.
}

This adds a code stating that arguments is not an array (array Class):

Copy Code code as follows:

Array.prototype.selfvalue = 1;
Alert (new Array (). Selfvalue);
function testaguments () {
alert (Arguments.selfvalue);
}

Run the code you will find that the first alert shows 1, which means that the array object has the Selfvalue property, the value is 1, and when you call the function testaguments, you will notice that the "undefined" is displayed, stating that the attribute is not arguments. That is, arguments is not an array object.
Here's a simple way to add a recommendation:
Copy Code code as follows:

Alert (arguments instanceof Array);
Alert (arguments instanceof Object);


Caller
Returns a reference to a function that calls the current function.
Functionname.caller
The 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, 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.
The following example illustrates the use of the caller property:
Copy Code code as follows:

Caller Demo {
function Callerdemo () {
if (Callerdemo.caller) {
var a= callerDemo.caller.toString ();
alert (a);
} else {
Alert ("This are a top function");
}
}
function Handlecaller () {
Callerdemo ();
}

callee

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

Example

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

A more general recursive function:
Copy Code code as follows:

var sum = function (n) {
if (1==n) return 1;
else return n + sum (n-1);

When invoked: Alert (SUM (100));
Inside the function contains a reference to sum itself, the function name is just a variable name, within the function call sum is equivalent to call
A global variable, it is not very good to reflect the call itself, then use callee will be a better way.

Apply and call

Their role is to bind the function to another object to run, the two only in the definition of the parameters of a different way:

Apply (Thisarg,argarray);

Call (Thisarg[,arg1,arg2 ...]);

That is, the this pointer within all functions is assigned to THISARG, which enables the function to run as a method of another object

Instructions for Apply

If Argarray is not a valid array or is not a arguments object, it will result in a typeerror.
If you do not provide any of the Argarray and Thisarg parameters, the Global object will be used as a thisarg,
and cannot be passed any parameters.

Description of call

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 supplied, the Global object is used as a thisarg

Related tips:

Application call and apply there is also a trick inside, is to use call and apply another function (class), the current
A function (class) has a method of another function (class) or a property, which can also be called inheritance. Look at the following example:
Copy Code code as follows:

Demo of Inheritance
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);
}

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

Incidentally, use apply to create a schema that defines a class in the JavaScript framework prototype.

The implementation code is as follows:
Copy Code code 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, that is, a class. But it's also a class.
constructor, where the initialize is invoked, which is the initialization function that is defined when the class is created. By such means,
You can implement the class creation pattern in prototype

Example:
Copy Code code 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 detailed information on prototype, please go to its official website to view it.

There is more to the comment on this understanding, I will no longer add, we can see a deeper understanding.
After reading the above code, you can, the following code is for some people who want to see the effect immediately see. Multiple tests.
Copy Code code as follows:

<script language= "JavaScript" >
/**//*
* Demo arguments usage, how to get real parameters and number of shapes
*/
function Argtest (a,b,c,d) {
var Numargs = arguments.length; Gets the numeric value of the parameter being passed.
var Expargs = argtest.length; Gets the numeric value of the expected parameter.
Alert ("Real parameter is:" +numargs)
Alert ("Number of shapes: +expargs")

Alert (Arguments[0])
Alert (argtest[0])//undefined no such use
}
Argtest (1,2)
Results: The real parameters were: 2; number of shapes: 4;1;undefined
Argtest (1,2,3,4,5)
Results: The real parameters were: 5; number of shapes: 4;1;undefined
/* Summary: JS parameter transfer is not like C # and other grammatical requirements must be consistent with the function definition, you can increase or decrease depending on the application of parameters, extreme conditions can not declare parameters, such as * *
var test = function () {
var a = 0;
var L = 0;
while (L<arguments.length)
{
A + + arguments[l];
l++;
}
alert (a);
}
Test ();//0
Test (1,2);//3

/**//*
* Arguments is not an array (array Class)
*/

Array.prototype.selfvalue = 1;
This is the most reviled of the original objects.
function testaguments () {
Alert ("arguments.selfvalue=" +arguments.selfvalue);
}
Alert ("Array.sefvalue=" +new Array (). Selfvalue);
/* The above call indicates that all array objects are selfvalue equal to 1*/
Testaguments ();
/* Results undefined that arguments is not an array type * *

/**//*
* Demonstrates the caller property of a function.
* Description: (current function). Caller: Returns a reference to a function that calls the current function
*/

function Callerdemo () {
if (Callerdemo.caller) {
var a= callerdemo.caller.arguments[0];
alert (a);
} else {
Alert ("This are a top function");
}
}
function Handlecaller () {
Callerdemo ();
}

Callerdemo ();
Result: this are a top function
Handlecaller ("Parameter 1", "Parameter 2");
Result: Parameter 1
/* Summary: Caller applied to function objects, can take to the upper level called function objects and parameters
*/

/**//*
* Demonstrates the callee property of a function.
* Description: Arguments.callee: Initial value is the function object being executed, for anonymous function
*/
function Calleedemo () {
alert (Arguments.callee);
}
Calleedemo ();
(function (ARG0,ARG1) {alert (Number of shapes: +arguments.callee.length)}) ();
/* Summary: can be used to achieve recursion, such as: * *
var i = 0;
var a = function () {
i + = arguments[0];
if (i>100| | i==0)
alert (i);
Else
Arguments.callee (i);
};
A (1);
The result is 128, which is actually 2 of the 7-time party


/**//*
* Demonstrating the use of Apply,call functions
* Description: The effect is to bind the function to another object to run, the two only in the definition of the parameters of the different ways:
* Apply (Thisarg,argarray);
* Call (Thisarg[,arg1,arg2 ...]);
* That is, all functions inside the this pointer will be assigned to Thisarg
*/

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

function Objectb () {
Alert ("Executive OBJECTB ()");
Call the Objecta () method, while all this in the Objecta constructor is substituted by this in the OBJECTB
Objecta.apply (this,arguments);//objecta.call (this);
alert (this.info);
}
OBJECTB (' parameter 0 ');
/* Summary: Usually with callee joint use * *
var i = 0
function A (b)
{
i++;
if (i>4)
return i;
Else
Return Arguments.callee.call (THIS,B);
}
Alert (A (0));

Issues about this scope

var value= "global variable";
function Obj () {
This.value= "Object! ";
}
function Fun1 () {
alert (this.value);
}
Fun1 ();
Result: global variable
fun1.apply (window);
Result: global variable, default This=window
Fun1.apply (New OBJ ());
Results: Object, This=new Obj (), this in obj refers to a 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.