Effective JavaScript Item 24 uses a variable to hold the arguments reference

Source: Internet
Author: User

this series as effective JavaScript 's reading notes.

Suppose you need a API used to traverse several elements, like this:


var it = values (1, 4, 1, 4, 2, 1, 3, 5, 6); It.next (); 1it.next (); 4it.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}};}

But the actual implementation is:


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

The reason for this is: for arguments The assignment of an object is implicitly complete.

in the Next method inside, using the arguments , however this arguments and the Values at the beginning of the method arguments is not an object.

The workaround is also simple, which is to arguments use a different variable for the reference. It can then be accessed by the nature of the closure in its nested function, as follows:


function values () {var i = 0, n = arguments.length, a = Arguments;return {hasnext:function () {return I < N;},next:fun Ction () {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 (); 1it.next (); 4it.next (); 1

Summarize:

  1. when used in a nested function arguments , note arguments the actual point
  2. you need to use an external function in a nested function. arguments , the external function's arguments object is saved to a variable, allowing the nested function to access

Effective JavaScript Item 24 uses a variable to hold the arguments reference

Related Article

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.