参数的生命周期

发布于 2024-11-18 10:27:38 字数 200 浏览 5 评论 0原文

摘自《JavaScript:权威指南,第 4 版》第 7.1 节:

请注意,这些参数变量仅在函数执行时定义;它们一旦函数返回就不会持续

这是真的吗?这是否意味着如果我打算在嵌套函数中使用某些参数,我必须将它们保存到局部变量中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分开我的手 2024-11-25 10:27:38

您可以像任何其他局部变量一样关闭参数,如下所示:

function test(v1) {
    return function() {
        alert(v1);
    }
}

var f = test("hello");
f();

这只是因为返回的函数关闭其词法范围内的变量。在正常情况下,是的,参数确实是函数的本地参数,并且一旦函数返回就不会保留。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文