7

所以我看到了一个函数,它的简单性非常坦率地说很漂亮,因为它允许您在匿名函数中找到全局对象(取决于当时的环境可能不是 window );但是,当您抛出 javascripts 的“使用严格”时;由于对关键字“this”的评估发生了变化,它会崩溃。有几种方法可以做到这一点?

(function () {
    var win = function () {
        return (function () {
                return this;
            }());
        };
    //win now points to the global object no matter where it is called.
}());

现在,如果在“使用严格”的上下文中调用这些函数,我们将失去所描述的功能,那么在 ES5 严格模式下是否有任何等价的功能?

以供参考

(function () {
    "use strict"
    //code here is in strict mode
}())
4

3 回答 3

8

解决方案:

var global = Function('return this')();

适用于所有浏览器、引擎、ES3、ES5、严格、嵌套范围等。

稍有变化将通过 JSLINT:

var FN = Function, global = FN('return this')();

讨论

请参阅如何在 JavaScript 中获取全局对象?

于 2011-09-07T23:56:40.930 回答
8
于 2011-09-02T23:36:59.507 回答
1

这是Perfection Kills的一个片段,使用全局评估。

var root = (function () {
    return this || (0 || eval)('this');
}());

兼容 ECMA3、ECMA5、严格模式等,通过 JSLint。

于 2012-01-12T15:44:35.747 回答