(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 }())
解决方法
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.“