在Javascript中引用窗口对象的目的是什么? [英] What's the purpose of referencing the window object in Javascript?
问题描述
窗口
对象的每个属性都是全局变量。这意味着你可以这样做:
Every property of the window
object is a global variable. This means you can do something like this:
window.foo = 42;
alert(foo); //alerts 42
var bar = 3;
alert(window["bar"]); //alerts 3
因此,我一直想知道引用<$的目的是什么这样的代码中的c $ c> window
Because of this, I've always wondered what the purpose was of referencing window
in code like this
if(window.prompt("Enter Password") === "secret") {
window.location.hash = "authorized";
window.open("secretPage.html");
}
当你可以省略窗口
并且代码完全相同:
when you could omit window
and have code that does exactly the same thing:
if(prompt("Enter Password") === "secret") {
location.hash = "authorized";
open("secretPage.html");
}
使用似乎也不一致;我几乎从未见过 window.alert
但我会经常看到 window.location
。
The use also seems inconsistent; I almost never see window.alert
but I'll frequently see window.location
.
人们喜欢引用窗口
来使他们的代码更加冗长吗?有什么理由可以做到这一点,我不知道吗?
Do people just like referencing window
to make their code more verbose? Is there some good reason for doing this that I don't know about?
推荐答案
有助于明确的一种情况是否会在函数内立即清除您想要修改全局变量的内容。例如:
One situation in which it helps to be explicit is that it will be immediately clear inside a function that you intend to modify a global variable. For example:
function blah() {
// a bunch of code preceding...
test = "aha!";
}
有人忘记申报 test
与 var
?或者这是对全球的故意修改?比较:
Did someone forget to declare test
with var
? Or is this intentional modification of a global? Compare:
function blah() {
// a bunch of code preceding...
window.test = "aha!";
}
现在可以立即清楚它的用途。当然,你知道,首先应该避免使用全局变量,但是你明白我的意思。
Now it's immediately clear what is intended. Of course, you know, globals should be avoided in the first place, but you get my point.
这篇关于在Javascript中引用窗口对象的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!