全局变量仅仅是“ window”对象上的属性吗? [英] Are global variables just properties on the `window` object?

查看:125
本文介绍了全局变量仅仅是“ window”对象上的属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我在浏览器上看到一个网站时,就会运行javascript实例。我可以在控制台(DevTools)中声明一个全局变量;

Whenever I see a website on the browser an instance of javascript is running. And I can declare a global variable in the console (DevTools);

var a = 1234567890; 

此变量已在全局范围内声明,因此我可以像这样获取变量的值;

This variable has been declared in global scope such that I can get the value of the variable like so;

> a 
1234567890

但是,我也可以这样做;

However, I can also do this;

> window.a 
1234567890 

我正确理解 window 对象是包含浏览器上网站实例内所有全局变量的对象吗?如果是,则窗口对象属于哪个范围?这让我有些困惑。

Am I understanding it correctly that the window object is the object that contains all the global variables within the website instance on the browser? If so to what scope does the window object belong? This is confusing me a little bit;

> window 
Window {top: Window, window: Window, location: Location, external:, ...}  
> window.window 
Window {top: Window, window: Window, location: Location, external:, ...}  
> window.window.window 
Window {top: Window, window: Window, location: Location, external:, ...}  

window 对象是最终的全局对象,并且是否具有名为 window 指的是自身?

Is the window object the ultimate global object and does that have an object called window that refers back to itself?

推荐答案


窗口对象是最终的全局对象,并且是否有一个称为 window 的对象可以返回自身?

Is the window object the ultimate global object and does that have an object called window that refers back to itself?

是的,是的。例如,这返回 true

Yes, and yes. This, for instance, returns true:

window.window.window.window.window === window.window;

如果您有兴趣,可以获取<$ c $的所有属性的列表。 c>带有的窗口对象(以及所有全局变量):

You can, if you are interested, get a list of all the properties of the window object (and hence all global variables) with Object.keys:

console.log(Object.keys(window));

但是请注意,如果您花太多时间在考虑全局变量,那么可能您的代码的架构问题。

Note, however, that if you are spending too much time thinking about global variables, there is probably a problem with the architecture of your code.

这篇关于全局变量仅仅是“ window”对象上的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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