The usage of parameter argument of JS indefinite function

Source: Internet
Author: User
Tags access properties

In this article, we introduce the method of using the implicit parameter of JS (Arguments,callee,caller).

Arguments

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

[function.] Arguments[n] Parameter
function: The name of the function object that is currently executing.
N: 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 arguments when a function call is 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 examples illustrate these properties in detail:

//use of Arguments objectsfunctionArgtest (A, b) {varI, S = "The Argtest function expected"; varNumargs = Arguments.length;//gets the numeric value of the passed parameter.    varExpargs = Argtest.length;//gets the numeric value of the desired parameter.    if(Expargs < 2) s+ = Expargs + "argument."; Elses+ = Expargs + "arguments."; if(Numargs < 2) s+ = Numargs + "was passed."; Elses+ = Numargs + "were passed."; S+= " " for(I =0; i < Numargs; i++) {//gets the contents of the parameter. s + = "Arg" + i + "=" + arguments + ""; }   return(s);//returns a list of parameters. }

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

Array.prototype.selfvalue = 1; alert (new  Array (). Selfvalue); function testaguments () {      alert (arguments.selfvalue);}
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.
Here is a simple way to add a recommendation: Alert (arguments instanceof Array);
Alert (arguments instanceof Object);

Caller
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, that is, the deserialized text of the function is displayed.

Note: function.tostring () can implement the function's anti-compilation functionality. More powerful with recursive functionality
The following example illustrates the use of the caller property:

// Caller Demo {function  Callerdemo () {    if  (callerdemo.caller) {         var a= callerDemo.caller.toString ();          alert (a);       Else {          alert ("This is a top function");}      } function Handlecaller () {      callerdemo ();}

Callee

Returns the function object being executed, which is the body of the specified function object. [function.] The Arguments.callee optional function parameter is the name of the function object that is currently executing. Indicates that the initial value of the Callee property is the Function object 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 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.

Example

//callee can print its ownfunctionCalleedemo () {alert (Arguments.callee);}//used to validate parametersfunctionCalleelengthdemo (arg1, arg2) {if(arguments.length==arguments.callee.length) {Window.alert ("Verify that the formal parameters and argument lengths are correct!" "); return; } Else{alert ("Argument length:" +arguments.length); Alert ("Parameter length:" +arguments.callee.length); }}//Recursive calculationvarsum =function(n) {if(n <= 0)                        return1;Else    returnn + arguments.callee (n-1)} More general recursive functions:varsum =function(n) {if(1==n)return1; Else returnn + 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, call sum inside the function is equivalent to calling a global variable, does not well reflect 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 implements the purpose of running the function as a method of another object. 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. The description of 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, then the Global object is used as a thisarg-related tip: Applying call and apply also has a technique in which another function (class) is applied with call and apply, The current function (class) has the 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 function () {          Window.alert (this. Member);      }} function Extend () {      Base.call (this);      Window.alert (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, with the following implementation code:

var Class = {    function() {    returnfunction() {        this. initialize.apply (this, arguments);     }}}

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. In this way, you can implement the class creation pattern example in prototype:

var vehicle=class.create (); Vehicle.prototype={      Initialize:function( Type) {        this.type=type;      }      Showself:function() {          alert (this. Type);      }} var moto=New vehicle ("moto"); moto.showself ();

Original link: http://www.jb51.net/article/46323.htm

Thanks to the original author!

The usage of parameter argument of JS indefinite function

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.