gpt4 book ai didi

javascript - JavaScript 中的作用域规则

转载 作者:行者123 更新时间:2023-11-30 07:23:42 25 4
gpt4 key购买 nike

我正在阅读JavaScript:完整引用,第三版作者:Thomas Powell; Fritz Schneider 对这些概念有详细的了解。

Scoping Rules

Outside of a function or object, variables are within the global space whether explicitly defined with var or not. Within a function or object, if the var statement is used, the defined variable will be local to the construct; without the statement, it will be global.

Commonly, JavaScript developers make assumptions about scoping rules with var that aren’t quite true. For example, a var statement found within a for loop does not scope that value to the loop. In this case, it is scoped to either the function it is within or to the global space if it is outside a function or an object.

只是为了看看结果会发生什么,我这样编码,

Global & Local Variables

当我在 Eclipse IDE 中按下 Ctrl+Space 以显示 JavaScript 提案时,为什么我能够在函数外部访问变量 jLocal?

根据作者的描述:

For example, a var statement found within a for loop does not scope that value to the loop. In this case, it is scoped to either the function it is within or to the global space if it is outside a function or an object.

最佳答案

因为在您的代码底部有:

...
jLocal = jLocal + j; // defined not in any functions
...

使其成为全局性的,但不必定义。

关于javascript - JavaScript 中的作用域规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com