javascript" use strict"和尼克发现全球功能 [英] javascript "use strict" and Nick's find global function

查看:148
本文介绍了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)


如果您需要访问全局对象而不对标识符窗口进行硬编码,则可以从任何级别的嵌套函数范围执行以下操作:

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中实际上不再是这种情况,
所以你必须采用代码处于严格模式时的不同模式。


例如,如果您正在开发库,则需要
,你可以将你的库代码包装成一个立即函数
(在第4章中讨论),然后从全局范围中将一个引用作为
参数传递给你的立即函数。

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之后)



Access to the Global Object (after 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模式,由Stoyan Stefanov
(O'Reilly)。版权所有2010 Yahoo!,Inc.,9780596806750。

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆