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:
- when used in a nested function arguments , note arguments the actual point
- 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