当我通过以下任一版本检索信息时,我得到了正确的结果:
window.screen.height
对比:
screen.height
是否需要/建议编写“窗口”。部分,或者我可以省略它吗?
这是否也适用于访问 document.properties/methods 和其他对象 - 我从不需要编写“文档”。部分(或我从中访问的任何对象)?
最佳答案
Is it required/adviced to write the 'window.' portion or can I leave it out?
这个具体示例(window
上的一个属性,在浏览器中)是一个特例;不,您不必编写 window
。 一般,您必须指定对象引用。
这是一个特例,因为 screen
是全局对象的一个属性,这使它成为一个全局变量。 window
也是全局对象的一个属性,它是对……全局对象的引用。所以 window.screen
和 screen
指的是同一个东西,全局对象上名为“screen”的属性。您还可以编写 window.window.screen
或 window.window.window.screen
等。 :-) 一些 ASCII 艺术可能会有用:
/-----------------\ | | v | +-------------------+ | | The Global Object | | +-------------------+ | | window |----/ +-------------------+ | screen |---------------->| The Screen Object | | (other globals).. | +-------------------+ +-------------------+
As you can see, the window
property on the global object refers back to the global object.
But again, it's a special case.
Side point: JavaScript does make it possible for you to use an implicit object reference when not dealing with the global object, using the with
statement
var obj = {foo: "bar"};
with (obj) {
console.log(foo); // "bar"
}
...但这可能会非常令人困惑,因此普遍不鼓励使用 with
(事实上,在新的(ish)“严格”语言模式中是不允许的)。
关于javascript - javascript 在使用它的 Prop /方法时是否需要引用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763827/