【发布时间】:2010-07-18 20:44:20
【问题描述】:
如果某个其他模块已加载,我想检查脚本。
if (ModuleName) {
// extend this module
}
但是如果ModuleName不存在,那throws。
如果我知道Global Object 是什么,我可以使用它。
if (window.ModuleName) {
// extend this module
}
但由于我希望我的模块同时适用于浏览器和node、rhino 等,我不能假设window。
据我了解,这在带有 "use strict" 的 ES 5 中不起作用;
var MyGLOBAL = (function () {return this;}()); // MyGlobal becomes null
这也会失败并抛出异常
var MyGLOBAL = window || GLOBAL
看来我只剩下了
try {
// Extend ModuleName
}
catch(ignore) {
}
这些情况都不会通过 JSLint。
我错过了什么吗?
【问题讨论】:
-
注意“var Fn = Function, global = Fn('return this')();”将不通过 JSLint,因为 JSLint 期望带有大写字母的函数是构造函数并使用“new”调用。不过,这是一个简单的解决方法。
-
这也通过了 JSLint,并且不需要额外的
Fn变量:var global = (function (fn) { return fn('return this'); }(Function)); -
@ahuth 你需要一个额外的
()。 -
你可以像这样获取全局对象(没有 eval 或 Function 构造函数):
var global = (function(){return this}).apply(null)。更多信息developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
注意:如果你使用严格模式,apply(null) 不会给出全局对象:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript global