javascript 全局变量 'var'并且没有“var”;
可能的重复:
在 JavaScript 中使用 var 和不使用 var 之间的区别
我知道我应该始终使用“var”来定义函数中的局部变量。
当我定义全局函数时,使用 'var' 有什么区别?
我在互联网上看到的一些代码示例使用
var globalVar = something;
globalVar = something;
有什么区别?
Possible Duplicate:
Difference between using var and not using var in JavaScript
I understand that I should always use 'var' to define a local variable in a function.
When I define a global function, what's the difference between using 'var' ?
Some of code examples I see over the internet use
var globalVar = something;
globalVar = something;
What's the difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,区别在于技术上,一个简单的赋值如
globalVar = 'something';
不会声明一个变量,该赋值只是在全局对象上创建属性,并且全局对象是作用域链中的最后一个对象,这一事实使其可解析。另一个区别是绑定的方式,变量被绑定为其环境记录的“不可删除”属性,例如:
我强烈鼓励您始终使用
var
语句,您的代码例如,在 ECMAScript 5 严格模式下会中断,不允许对未声明的标识符进行赋值以避免隐式全局。Well, the difference is that technically, a simple assignment as
globalVar = 'something';
doesn't declare a variable, that assignment will just create a property on the global object, and the fact that the global object is the last object in the scope chain, makes it resolvable.Another difference is the way the binding is made, the variables are bound as "non-deletable" properties of its environment record, for example:
I would strongly encourage you to always use the
var
statement, your code for example will break under ECMAScript 5 Strict Mode, assignments to undeclared identifiers are disallowed to avoid implicit globals.简而言之:全球背景下没有差异**。
Long:全局上下文的变量对象是全局上下文本身。这就是为什么我们可以在函数或eval上下文中访问全局
变量
和方法
。但是,var
语句只是确保您在当前上下文中定义变量,因此在全局上下文中省略该变量没有什么区别。 异常:ES5 严格模式在看到没有var
的声明时可能会抛出错误。**
唯一的区别是,
var
将声明一个在当前(执行)上下文中没有定义的变量。这发生在 js 解析时,因此引擎知道上下文中有一个具有该名称的变量。省略var
最终将导致从全局对象
直接访问属性。Short: There is no difference in the global context**.
Long: The Variable object for the global context is the global context itself. That is why we can just access global
variables
andmethods
within a function-, or eval context. However, thevar
statement just makes sure you're defining a variable in the current context, so it makes no difference by omitting that in the global context. Exception: ES5 strict mode will probably throw an error when it sees a declaration withoutvar
.**
the only difference is, that
var
will declare a variable without definition in the current (execution) context. This happens at js parse time, so the engine knows that there is a variable with that name available in the context. Omittingvar
will end up in a direct property access from theglobal object
.