如何在JS中引用全局命名空间

How to refer to Global name space in JS

本文关键字:引用 全局 命名空间 JS      更新时间:2023-09-26

什么是JS全局命名空间的变量,它有一个引用,我可以改变它吗?(免责声明是的,我知道这是很糟糕的做法,如果我可以的话)

在浏览器中,可以通过window访问。

alert(window.document === document);    // true

我只是试图改变它使用分配在谷歌浏览器,但令人惊讶的是,它没有效果。

Javascript在浏览器中的全局命名空间/对象是window。据我所知,你可以改变它,但是不要这样做。

编辑:我错了。值得庆幸的是,你不能改变它(例如window = {};没有效果,至少不是在Chrome)。

在不以ECMAScript 3.1严格模式运行的JavaScript中,您可以使用关键字this引用全局对象,但仅当不执行具有对象上下文的函数内的代码时。

// In global scope:
alert(this.Math === Math);  //-> true
function test() {
    alert(this.Math === Math);
}
test();     //-> true
var someObj = {};
test.call(someObj); //-> false, `this` is `someObj`

在浏览器中,正如其他答案所提到的,window对象也是全局对象。

alert(this === window); //-> true
alert(this.alert === window.alert); //-> true

全局命名空间有以下名称:

window//最常出现

top//在某些情况下

self

parent//在某些情况下

this//在某些情况下