Aki*_*idi 7 javascript ecmascript-5
所以我看到一个函数,它的简单性非常坦率,因为它允许你在匿名函数中找到全局对象(当时依赖于环境可能不是窗口); 但是当你抛出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.
}());
Run Code Online (Sandbox Code Playgroud)
现在,如果在"use strict"的上下文中调用它们,我们将失去所描述的功能,是否有任何可以在ES5严格模式下完成的等效操作?
以供参考
(function () {
"use strict"
//code here is in strict mode
}())
Run Code Online (Sandbox Code Playgroud)
如果您需要访问全局对象而不对标识符窗口进行硬编码,则可以从任何级别的嵌套函数范围执行以下操作:
var global = (function () {
return this;
}());
Run Code Online (Sandbox Code Playgroud)
这样你就可以随时获取全局对象,因为在作为函数调用的内部函数中(也就是说,不是作为new的限制器),这应该始终指向全局对象.
在严格模式下ECMAScript 5中实际上不再是这种情况,因此当您的代码处于严格模式时,您必须采用不同的模式.
例如,如果您正在开发一个库,您可以将库代码包装在一个立即函数中(在第4章中讨论),然后从全局范围中将一个引用作为参数传递给您的立即函数.
通常,全局对象作为参数传递给immediate函数,以便它可以在函数内部访问而无需使用窗口:这种方式使代码在浏览器之外的环境中更具互操作性:
(function (global) {
// access the global object via `global`
}(this));
Run Code Online (Sandbox Code Playgroud)
"JavaScript模式,Stoyan Stefanov(O'Reilly).版权所有2010 Yahoo!,Inc.,9780596806750."
var global = Function('return this')();
Run Code Online (Sandbox Code Playgroud)
适用于所有浏览器,引擎,ES3,ES5,严格,嵌套范围等.
略有变化将通过JSLINT:
var FN = Function, global = FN('return this')();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2921 次 |
最近记录: |