且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript" use strict"和尼克发现全球功能

更新时间:2022-05-29 08:35:04

访问全局对象(在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。