[英]Javascript Module Pattern Uncaught Reference Error
I've been following this tutoral, and when referencing Module as an argument in ModuleTwo, everything works fine until I comment out Module . 我一直在关注此教程,当在ModuleTwo中将Module用作参数引用时,一切正常, 直到我注释掉Module为止 。
My understanding is that the double pipes || 我的理解是双管道|| and empty object {} will create an empty object in place of Module if it's undefined, but instead I'm getting an error in the console.
如果未定义,则空对象{}将创建一个空对象来代替Module,但在控制台中却出现错误。
var Module = (function () {
var privateMethod = function () {
// private
};
var someMethod = function () {
// public
};
var anotherMethod = function () {
// public
};
return {
someMethod: someMethod,
anotherMethod: anotherMethod
};
})();
var ModuleTwo = (function (Module) {
Module.extension = function () {
// another method!
};
return Module;
})(Module || {});
When you apply the function defining your 2nd module to (Module || {})
, the symbol Module
cannot be resolved if the Module
hasn't been declared earlier, which always gives a JavaScript error. 当您应用定义你的第二模块的功能
(Module || {})
符号Module
不能,如果解决Module
尚未早些时候宣布,它总是给人一种JavaScript错误。 If you want the 2nd Module to be defined even in the absence of the first Module, try the following: 如果即使在没有第一个模块的情况下也要定义第二个模块,请尝试以下操作:
var ModuleTwo = (function(Module) {
...
})(typeof Module == 'object' ? Module : {} );
Basically, there's an error in the tutorial. 基本上,本教程中有一个错误。 One way to make things work was suggested by rplantiko, but it might be easier to just write
window.Module || {}
rplantiko提出了一种使事情正常运行的方法,但仅编写window可能会更容易
window.Module || {}
window.Module || {}
instead of Module || {}
window.Module || {}
代替Module || {}
Module || {}
. Module || {}
。
How things work here: 这里的运作方式:
undefined
. undefined
。 However, referencing a variable that hasn't been declared yields ReferenceError
(so your understanding was a little bit off there). ReferenceError
(因此,您的理解还差一点)。 window
object. window
对象上。 Module
in the tutorial is a global variable, because it's declared outside all functions, so you can access it via window.Module
, which will not cause ReferenceError
if undefined (per previous point). Module
是全局变量,因为它是在所有函数外部声明的,因此您可以通过window.Module
对其进行访问,如果未定义(按上一点),则不会导致ReferenceError
。 It might be a good practice to explicitly assign to window
any global variable you define (eg, do window.Module = (function () { …
if you intend to make Module
global), but that's arguable and out of scope of this discussion. 最好将您定义的任何全局变量显式分配给
window
(例如,执行window.Module = (function () { …
如果您打算使Module
成为全局变量),这是一个好习惯,但这是有争议的,不在本讨论范围之内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.