javascript“使用严格”和尼克的查找全局函数
所以我看到了一个函数,坦率地说,它的简单性非常漂亮,因为它允许您在匿名函数中找到全局对象(取决于当时的环境,可能不是 window );然而,当你抛出 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.
}());
现在,如果在“use strict”的上下文中调用它们,我们就会失去所描述的功能,是否有任何可以在 ES5 严格模式下完成的等效功能?
供参考
(function () {
"use strict"
//code here is in strict mode
}())
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.
}());
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?
For reference
(function () {
"use strict"
//code here is in strict mode
}())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案:
适用于所有浏览器、引擎、ES3、ES5、严格、嵌套范围等。
轻微的变化将通过 JSLINT:
讨论
请参阅 如何在 JavaScript 中获取全局对象?
Solution:
Works in all Browsers, Engines, ES3, ES5, strict, nested scope, etc.
A slight variation will pass JSLINT:
Discussion
See How to get the global object in JavaScript?
访问全局对象(ES5之前)
严格模式下的 ECMAScript 5 实际上不再是这种情况,
因此,当您的代码处于严格模式时,您必须采用不同的模式。
访问全局对象(ES5之后)
“JavaScript 模式,作者:Stoyan Stefanov
(奥莱利)。版权所有 2010 Yahoo!, Inc.,9780596806750。”
Access to the Global Object (before ES5)
This is actually no longer the case in ECMAScript 5 in strict mode,
so you have to adopt a different pattern when your code is in strict mode.
Access to the Global Object (after ES5)
“JavaScript Patterns, by Stoyan Stefanov
(O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”
这是 Perfection Kills 的片段,使用全局 eval。
ECMA3、ECMA5、严格模式等兼容,通过 JSLint。
Here's a snippet from Perfection Kills, using global eval.
ECMA3, ECMA5, Strict mode, etc compatible, passes JSLint.