什么是全局变量,并在JavaScript中window.variable之间的区别? [英] What's the difference between a global var and a window.variable in javascript?

查看:148
本文介绍了什么是全局变量,并在JavaScript中window.variable之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看Backbone.js的文件,看到很多code来分配的属性窗口的对象:

I'm reading the backbone.js documents and seeing a lot of code that assigns attributes to the window object:

window.something = "whatever";

什么是调用这个code,只是分配变量,创建一个全局变量,这样的区别:

what's the difference between calling this code, and just assigning the variable and creating a global var, like this:

something = "whatever";

我假设有某种范围的不同,和/或对象所有权差异(窗口作为所有者VS没有),但我感兴趣的两个,为什么我会用窗口VS不使用它的细节。

i assume there is some kind of scope different, and/or object ownership difference (window being the owner vs not) but i am interested in the detail between the two and why i would use window vs not use it.

推荐答案

没有区别。它们都具有相同的效果(在浏览器中,其中窗口是全球范围内的 1 )。

No difference. They both have the same effect (In the browser, where window is the global context1).


  • window.foo =栏设置属性窗口

  • = foo的栏表示无论一个错字或故意全球性的。

  • window.foo = "bar" sets the property foo on window.
  • foo = "bar" indicates either a typo or intentionally global.

由于我必须仔细检查它是否是一个错字或没有,我个人觉得更多的阅读设置 window.foo 直接

Since I have to double check whether it's a typo or not, I personally find it more readable to set window.foo directly.

此外,在ES5严格模式,富=栏是非法转让,因为未声明并抛出一个错误

Also, in ES5 strict mode, foo = "bar" is an illegal assignment because foo is not declared and will throw a Error.

编辑:

由于在评论中指出,富=栏看起来一路上涨的范围链变量栏,如果它的发现。如果它没有找到,它会创建一个新的全局变量。

As noted in the comments, foo = "bar" will look all the way up the scope chain for the variable foo and re-assign it with "bar" if it's found. If it's not found, it will create a new global variable.

还与 window.foo =栏你只是分配一个属性的对象,可以使用删除窗口中删除。富

Also with window.foo = "bar" you're just assigning a property to an object, which can be deleted using delete window.foo.

在ES5严格模式下它的无效删除的变量。

In ES5 strict mode it is invalid to delete a variable.

1 在其他环境中,如Node.js的和Web工作者,有可能是全局对象的另一个名称,窗口不可以存在于所有。 Node.js的用途全球和Web工作者使用

1 In other environments, such as node.js and Web Workers, there may be another name for the global object and window may not exist at all. Node.js uses global and Web Workers use self.

这篇关于什么是全局变量,并在JavaScript中window.variable之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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