2

Excerpt from section 7.1 of "JavaScript: The Definitive 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?

4

1 に答える 1

2

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.

于 2011-07-03T19:33:45.303 に答える