获取 global object 句柄的推荐方法是什么?在 ES5 严格模式下在未知的主机环境?
ECMAScript 没有提供引用我所知道的全局对象的内置方法。如果是的话,这就是我正在寻找的答案。
在已知环境中,全局对象通常具有自引用属性。由于全局对象是 VO对于全局作用域,全局对象的属性是全局变量,因此我们可以使用它们从任何地方获取全局对象的句柄:
在网络浏览器中,我们可以使用
window
或self
。在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/