The concept of caller,callee,call,apply in JavaScript [reprint]

Source: Internet
Author: User
Tags access properties

Before referring to the above concepts, I would like to start by talking about the implicit parameters of the functions in javascript: arguments

Arguments:

The object represents the function being executed and the parameters of the function that called it.

[function.] Arguments[n] parameter function: option. The name of the Function object that is currently executing.
N: Option, the 0-based parameter value index to pass to the Function object.
Description arguments: A hidden object that was created in addition to the specified arguments when the function call was made. Arguments is an array-like but not an array object, saying that it resembles an array because it has an array of access properties and methods, which can be accessed by arguments[n] to access the value of the corresponding single parameter and has the length property of the array. Also, the arguments object stores the arguments that are actually passed to the function, not limited to the list of arguments defined by the function declaration, and the arguments object cannot be created explicitly. The arguments object is available only when the function starts. The following example illustrates these properties in detail: The use of//arguments objects.

Here you add a code that illustrates that arguments is not an array class:
The usage of the arguments object.

1 function Argtest (A, b) {
2 var i, S = "The Argtest function expected";
3 var Numargs = arguments.length; Gets the numeric value of the passed parameter.
4 var Expargs = argtest.length; Gets the numeric value of the desired parameter.
5 if (Expargs < 2)
6 S + = Expargs + "argument.";
7 Else
8 S + = Expargs + "arguments.";
9 if (Numargs < 2)
Ten S + = Numargs + "was passed.";
One else
s + = Numargs + "were passed.";
s + = "\ n"
+ for (i =0; i < Numargs; i++) {//Get parameter contents.
+ S + = "Arg" + i + "=" + arguments[i] + "\ n";
16}
+ return (s); Returns a list of parameters.
18}


Here you add a code that illustrates that arguments is not an array class:

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


Running 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 find that "undefined" is displayed, indicating that the property is not arguments. That is, arguments is not an array object.

Caller


Returns a reference to the function that called the current function.
Functionname.caller
The 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, then caller contains null. If you use the Caller property in a string context, the result is the same as functionname.tostring, which means that the function is displayed

The anti-compilation text. The following example illustrates the use of the caller property:

1//Caller Demo {
2 function Callerdemo () {
3 if (Callerdemo.caller) {
4 var a= callerDemo.caller.toString ();
5 alert (a);
6} else {
7 alert ("This is a top function");
8}
9}
Ten function Handlecaller () {
Callerdemo ();
12}

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 the arguments object that represents a reference to the function object itself, which facilitates the recursion of anonymous functions or guarantees the encapsulation of functions, such as the sum of the natural numbers of 1 to n for the recursive calculation of the example below. 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 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.

Example

1//callee can print its own
2 function Calleedemo () {
3 alert (Arguments.callee);
4}

1//For validating parameters
2 function Calleelengthdemo (arg1, arg2) {
3 if (arguments.length==arguments.callee.length) {
4 Window.alert ("Verify that the parameters and argument lengths are correct!") ");
5 return;
6} else {
7 alert ("Argument length:" +arguments.length);
8 alert ("Parameter length:" +arguments.callee.length);
9}
10}
11//Recursive calculation
var sum = function (n) {
if (n <= 0)
return 1;
All else
return n +arguments.callee (n-1)
17}
18 Comparison of general recursive functions:
19
var sum = function (n) {
if (1==n) return 1;
+ else return n + sum (n-1);


When invoked: Alert (SUM (100));
Where the function contains a reference to the sum itself, the function name is just a variable name, and calling sum inside the function is equivalent to calling
A global variable, not a good representation of the call itself, when using callee will be a better method.

Apply and call:

Their role is to bind the function to another object to run, and the two differ only in the way that the parameter is defined:

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

That is, the this pointer inside all functions is assigned a value of Thisarg, which enables the purpose of running a function as a method of another object

Description of Apply:

If Argarray is not a valid array or is not a arguments object, it will result in a TypeError. If none of the Argarray and Thisarg parameters are provided, then the Global object is 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 a new object specified by Thisarg.
If the Thisarg parameter is not provided, then the Global object is used as the Thisarg

Related tips:

Applying call and apply there is also a technique in which the current function (class) has a method or property of another function (class), which is also called "Inheritance", when another function (class) is applied by calling and apply.

”。 Look at the following example:

1//Inherited Demo
2 function base () {
3 This.member = "Dnnsun_member";
4 This.method = function () {
5 Window.alert (This.member);
6}
7}
8 function Extend () {
9 Base.call (this);
Ten Window.alert (member);
Window.alert (This.method);
12}

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:

1 var Class = {
2 Create:function () {
3 return function () {
4 this.initialize.apply (this, arguments);
5}
6}
7}

Parsing: From the code perspective, the object contains only one method: Create, which returns a function, the class. But this is also the constructor of the class, where initialize is called, and this method is the initialization function defined at the time the class is created. Through such a path

Can implement the class creation pattern in prototype

Example:

1 var vehicle=class.create ();
2 vehicle.prototype={
3 Initialize:function (type) {
4 This.type=type;
5}
6 showself:function () {
7 Alert ("This vehicle is" + this.type);
8}
9}
10
One-to-one var moto=new vehicle ("moto");
Moto.showself ();

For more detailed information about prototype, please visit its official website.

Demo

1 function Myfuncone () {
2 THIS.P = "myfuncone-";
3 this. A = function (ARG) {
4 alert (THIS.P + arg);
5}
6}
7
8 function Myfunctwo () {
9 THIS.P = "myfunctwo-";
Ten this. B = function (ARG) {
One alert (THIS.P + arg);
12}
13}
function Test () {
var obj1 = new Myfuncone ();
var obj2 = new Myfunctwo ();
Obj1.                       A ("TestA"); Show Myfuncone-testa
Obj2.                        B ("Testb"); Show Myfunctwo-testb
Obj1.          A.apply (Obj2, ["TestA"]); Display Myfunctwo-testa, where [TestA] is an array of only one element
Obj2.          B.apply (Obj1, ["TESTB"]); Display Myfuncone-testb, where [TESTB] is an array of only one element
Obj1.             A.call (Obj2, "TestA"); Show Myfunctwo-testa
Obj2.             B.call (obj1, "Testb"); Show Myfuncone-testb
23}
Test ();

The concept of caller,callee,call,apply in JavaScript [reprint]

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.