和尼克发现全球功能

和尼克发现全球功能

本文介绍了javascript" use strict"和尼克发现全球功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我看到一个函数,它的简单性非常漂亮,因为它允许你在匿名函数中找到全局对象(当时依赖于环境可能不是窗口);但是当你抛出javascripts的use strict时;由于关键字'this'的变化评估,它会崩溃。有几种方法可以做到这一点?

So I saw a function that was, quite frankly beautiful in its simplicity as it allowed you to find the global object ( which depending on environ at the time may NOT have been window ) while within an anonymous function; however when you throw javascripts' "use strict"; mode it crumbles, due to the evaluation of the keyword 'this' changing. There were a few ways to accomplish this?

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

现在,如果在use strict的上下文中调用它们,我们将失去所描述的功能,是有没有可以在ES5严格模式下完成的等价物?

Now, if these are called within the context of "use strict" we lose the functionality described, is there any equivalent that can be done in ES5 strict mode?

供参考

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


推荐答案

访问全局对象(在ES5之前)



Access to the Global Object (before ES5)



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



在严格模式的ECMAScript 5中实际上不再是这种情况,
所以你必须采用代码处于严格模式时的不同模式。



访问全局对象(在ES5之后)



Access to the Global Object (after ES5)



(function (global) {
    // access the global object via `global`
}(this));

JavaScript模式,由Stoyan Stefanov
(O'Reilly)。版权所有2010 Yahoo!,Inc.,9780596806750。

这篇关于javascript" use strict"和尼克发现全球功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:21