問題描述
我正在閱讀backbone.js 文檔并看到很多將屬性分配給窗口對象的代碼:
I'm reading the backbone.js documents and seeing a lot of code that assigns attributes to the window object:
window.something = "whatever";
調用此代碼與僅分配變量并創建全局變量有什么區別,如下所示:
what's the difference between calling this code, and just assigning the variable and creating a global var, like this:
something = "whatever";
我假設存在某種不同的范圍和/或對象所有權差異(窗口是所有者而不是所有者),但我對兩者之間的細節以及為什么我會使用窗口而不是使用它感興趣.
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.
推薦答案
沒有區別.它們都具有相同的效果(在瀏覽器中,window
是全局上下文1).
No difference. They both have the same effect (In the browser, where window
is the global context1).
window.foo = "bar"
在window
上設置屬性foo
.foo = "bar"
表示錯字或故意全局.
window.foo = "bar"
sets the propertyfoo
onwindow
.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 嚴格模式下,foo = "bar"
是非法賦值,因為 foo
沒有被聲明并且會拋出 Error
.
Also, in ES5 strict mode, foo = "bar"
is an illegal assignment because foo
is not declared and will throw a Error
.
如注釋中所述,foo = "bar"
將在范圍鏈中查找變量 foo
并用 重新分配它"bar"
如果找到的話.如果沒有找到,它會創建一個新的全局變量.
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 = "bar"
您只是將屬性分配給對象,可以使用 delete 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 嚴格模式下 invalid delete
一個變量.
In ES5 strict mode it is invalid to delete
a variable.
1 在其他環境中,例如node.js 和Web Workers,全局對象可能有另一個名稱,而window
可能根本不存在.Node.js 使用 global
而 Web Workers 使用 self
.
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有什么區別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!