所以我看到了一个函数,坦率地说,它的简单性非常漂亮,因为它允许您在匿名函数中找到全局对象(这取决于当时的环境,可能不是 window );但是,当您抛出 javascripts 的“使用严格”时;由于对关键字“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 模式,作者:Stoyan Stefanov (奥莱利)。版权所有 2010 Yahoo!, Inc.,9780596806750。”
关于javascript "use strict"和尼克的查找全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290086/