Learn about javascript's arguments object_javascript skills

Source: Internet
Author: User
Learn about the arguments object of javascript. For more information, see 1. What is arguments?

Arguments is a built-in object in JavaScript. It is odd and often overlooked, but it is actually very important. All major js function libraries use the arguments object. Therefore, the agruments object must be familiar to javascript programmers. In javascript Functions, the identifier arguments has a special meaning. It is a special attribute of the called object and is used to reference the Arguments object. The Arugments object is like an array. Note that it is just like it is not.

In javascript Functions, arguments is an array(It is not a real array. It is an Arguments object, which is emphasized again)Similarly, the length attribute indicates the number of parameters passed to the function.

In javascript, the Arguments object is the actual parameter of the function. The length of the arguments object is determined by the number of Arguments rather than the number of arguments. Parameters are the variables used to re-store the memory space in the function, but they do not overlap with the memory space of the arguments object.

Js will not take the initiative to determine the number of parameters you pass to the function. If you pass more parameters, the excess parameters will not be used. If you pass less parameters, the parameter value that is not passed is undefined. so we can use the length attribute of arguments to check whether the actual parameters of the correct number are used when calling the function, because javascript will not do these tasks for you.

Function f (x, y, z) {// first check whether the number of passed parameters is correct if (arguments. length! = 3) {throw new Error ("function f called with" + arguments. length + "arguments");} // run the real function below}

2. Create a variable parameter list function using arguments

Arguments also provides us with the possibility of passing an arbitrary number of parameters for a function:

For example, I want to use a display () function to calculate the total salary of each employee in a company. Yes, you can specify the number of parameters, but only if you want to upload a number, because I am too lazy to judge inside the function.

Function display () {var sum = 0; // total value for (var I = 0; I ');} // display (5000,) of Company ); // Company B display (10000 );

How is it? This method is very clever, right?

It indicates that arguments is consistent with the actually passed form parameter:

When both arguments and Values exist, the two values change one value synchronously, that is, all values of the two.

function f(a, b, c){ alert(arguments.length); // result: "2" a = 100; alert(arguments[0]);  // result: "100" arguments[0] = "qqyumidi"; alert(a);     // result: "qqyumidi" alert(c);     // result: "undefined" c = 2012; alert(arguments[2]);  // result: "undefined"}f(1, 2);

3. Never modify the arguments object

The relationship between declared parameters and arguments in the function is very fragile. Each declared parameter is actually a reference to the corresponding position in the arguments object.

It is worth noting that in the strict mode of ES5, the parameter declared by the function does not reference arguments:

function strict(x) { "use strict"; arguments[0] = "modified"; return x === arguments[0];}function nonstrict(x) { arguments[0] = "modified"; return x === arguments[0];}strict("unmodified"); // falsenonstrict("unmodified"); // true

Because in strict and non-strict mode, the relationship between the parameters declared by the function and arguments is inconsistent, It is the safest way to avoid problems without modifying the arguments object.

If you really need to modify the arguments object, you can assign a copy of the arguments object first:

Var args = []. slice. call (arguments );
When the slice method does not accept any parameters, it performs the copy operation. The obtained args is also a real array object. At the same time, there is no connection between args and function declaration parameters, and it is safe to operate on them.

4. A variable to save arguments references

Assume that an API is required to traverse several elements, as shown below:

var it = values(1, 4, 1, 4, 2, 1, 3, 5, 6); it.next(); // 1 it.next(); // 4 it.next(); // 1 

The corresponding implementation can be:

function values() {  var i = 0, n = arguments.length;  return {   hasNext: function() {    return i < n;   },   next: function() {    if (i >= n) {     throw new Error("end of iteration");    }    return arguments[i++]; // wrong arguments   }  }; } 

However, the actual execution is:

var it = values(1, 4, 1, 4, 2, 1, 3, 5, 6); it.next(); // undefined it.next(); // undefined it.next(); // undefined 

The reason is:The values assigned to the arguments object are implicitly completed. Arguments is used inside the next method. However, the arguments at the beginning of the arguments and values methods are not an object. The arguments object here is the function next.

The solution is simple, that is, to reference the arguments to be accessed using another variable. Then, you can access the nested functions by using the nature of the closure, as shown below:

function values() {  var i = 0, n = arguments.length, a = arguments;  return {   hasNext: function() {    return i < n;   },   next: function() {    if (i >= n) {     throw new Error("end of iteration");    }    return a[i++];   }  }; } var it = values(1, 4, 1, 4, 2, 1, 3, 5, 6); it.next(); // 1 it.next(); // 4 it.next(); // 1 

5. The callee attribute of the arguments object:

The callee attribute of arguments is used to reference the currently executed function, which is very beneficial to the Untitled function call itself.

First, implement recursive functions using the name function expression:

// Specify the function name for the function directly. Recursive function var result = function fact (x) {if (x <= 1) return 1; else return x * fact (x-1 );};

In this section, I mentioned that the function can be directly called. In this way, recursion can be easily called by yourself.

Now, the callee of arguments can be easily implemented.

// Use the function directly, using arguments. the callee attribute implements the recursive function var result = function (x) {if (x <= 1) return 1; return x * arguments. callee (x-1 );};

At last, I would like to remind you that, since this arguments is so powerful, we should not name the variable arguments. In fact, arguments is one of the reserved words in javascript. Well.

Last, I would like to add:

Difference caller

Returns a reference to the function that calls the current function.

  • -FunctionName. caller
  • -The functionName object is the name of the executed function.

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.

Code:

Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/--> // caller demo {function callerDemo () {if (callerDemo. caller) {var a = callerDemo. caller. toString (); alert (a) ;}else {alert ("this is a top function") ;}} function handleCaller () {callerDemo () ;}handlecaller (); // The definition of handleCaller is displayed.

The above is an introduction to the arguments object of javascript, and I hope it will help you learn it.

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.