Lifetime of parameters
Excerpt from section 7.1 of "JavaScript: The Defin开发者_如何转开发itive Guide, 4th Edition":
Note that these parameter variables are defined only while the function is being executed; they do not persist once the function returns.
Is that really true? Does that mean I have to save some parameters to local variables if I intend to use them from within nested functions?
You can close over parameters just as with any other local variable, like so:
function test(v1) {
return function() {
alert(v1);
}
}
var f = test("hello");
f();
This is only because the returned function closes over the variables in its lexical scope. In the normal case, yes, it's true that parameters are local to a function and do not persist once the function returns.
精彩评论