javascript“use strict”和Nick找到全局函数

前端之家收集整理的这篇文章主要介绍了javascript“use strict”和Nick找到全局函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我看到一个函数,它的简单性非常坦率,因为它允许你在匿名函数中找到全局对象(当时依赖于环境可能不是窗口);但是当你抛出 javascripts’“use strict”时;由于评估关键字’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严格模式下完成的等效操作?

以供参考

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

解决方法

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

If you need to access the global object without hard-coding the identifier window,you can do the following from any level of nested function scope:

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

This way you can always get the global object,because inside functions that were invoked
as functions (that is,not as constrictors with new) this should always point to
the global object.

在严格模式下,ECMAScript 5实际上不再是这种情况,
因此,当您的代码处于严格模式时,您必须采用不同的模式.

For example,
if you’re developing a library,you can wrap your library code in an immediate function
(discussed in Chapter 4) and then from the global scope,pass a reference to this as a
parameter to your immediate function.

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

Commonly,the global object is passed as an argument to the immediate function so
that it’s accessible inside of the function without having to use window: this way makes
the code more interoperable in environments outside the browser:

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

“JavaScript模式,由斯托扬斯特凡诺夫(O’Reilly出版).版权所有2010 Yahoo!,Inc.,9780596806750.“

猜你在找的JavaScript相关文章