带有“var”且没有“var”的javascript全局变量 [英] javascript global variable with 'var' and without 'var'

查看:134
本文介绍了带有“var”且没有“var”的javascript全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用var和不使用JavaScript中的var之间的区别


我知道我应该总是使用'​​var'来定义函数中的局部变量。



当我定义一个全局函数时,使用'var'之间有什么区别?



我在互联网上看到的一些代码示例

  var globalVar = something; 
globalVar =某事;

有什么区别?

解决方案

嗯,不同之处在于技术上,一个简单的赋值为 globalVar ='something'; 声明一个变量,该赋值只会在全局对象上创建一个属性,并且全局对象是作用域链中的最后一个对象,这使得它可以解析。 / p>

另一个区别在于绑定的方式,变量被绑定为其环境记录的不可删除属性,例如:

  var global1 ='foo'; 
删除this.global1; // false

global2 ='bar';
删除this.global2; // true

我强烈建议您始终使用 var 语句,例如,您的代码将在ECMAScript 5严格模式下中断,不允许对未声明的标识符进行赋值以避免隐式全局


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?

解决方案

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:

var global1 = 'foo';
delete this.global1; // false

global2 = 'bar';
delete this.global2; // true

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.

这篇关于带有“var”且没有“var”的javascript全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆