javascript - 在严格模式下获取未知环境中全局对象的引用

标签 javascript global ecmascript-5 ecma262 strict-mode

获取 global object 句柄的推荐方法是什么?在 ES5 严格模式下在未知的主机环境

ECMAScript 没有提供引用我所知道的全局对象的内置方法。如果是的话,这就是我正在寻找的答案。

已知环境中,全局对象通常具有自引用属性。由于全局对象是 VO对于全局作用域,全局对象的属性是全局变量,因此我们可以使用它们从任何地方获取全局对象的句柄:

  • 在网络浏览器中,我们可以使用 windowself

  • 在node.js中,我们可以使用global

但是,并非所有主机环境都是如此。据我所知,Windows Script Host没有提供任何访问全局对象的方法。在 WSH 中获取全局对象的推荐方法似乎是在不解析为对象的上下文中使用 this 关键字。例如:

var GLOBAL = (function(){return this}());

此技术适用于任何主机环境,但不适用于严格模式,因为未定义的 this 不会引用 strict mode 中的全局对象。 :

If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object (10.4.3, 11.1.1, 15.3.4.3, 15.3.4.4).

正如预期的那样,以下代码会导致未定义:

(function(){
    "use strict";
    var GLOBAL = (function(){return this}());
    console.log(GLOBAL);
}());
<小时/>

那么,无论严格模式如何,在任何环境中获取全局对象句柄的正确方法是什么?

顺便说一句,我当前的方法是嗅探引用全局对象的全局变量,如下所示:

var self, window, global = global || window || self;

...然后只需使用global。我认为这是一个糟糕的解决方案,原因有很多,其中大部分都是相当明显的,而且它没有解决 WSH 问题。

最佳答案

在 ES5 中,您可以通过间接 eval 调用从严格模式中获取对全局对象的引用:

"use strict";
var global = (1,eval)('this');

看看my article ;特别是在这个section on strict mode .

关于javascript - 在严格模式下获取未知环境中全局对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642491/

相关文章:

javascript - 使用appendChild、setAttribute等格式化href链接

java - 全局变量隐藏在执行的操作中

c - as400 ILE C 全局变量多重重定义

javascript - 有没有办法检查lodash中一系列对象的对象中是否为空或未定义

Javascript:提取 URL 的一部分,清理它,然后在 Flash 容器的 html 嵌入代码中使用它

javascript - $watch 或 ng-model 绑定(bind)问题?

javascript - map 对象中的值没有增加

javascript - D3更新画笔的比例不更新画笔

python - 如何使我的类中的变量成为全局变量,但仅使其在类中成为全局变量?

javascript - 无论如何让实例共享相同的功能但同时具有私有(private)变量?