支持相互依赖的 JavaScript 模块模式
看来使用以下 javascript 模块模式,不可能有相互依赖的模块:
var AA = (function(module, BB){
module.sayHello = function(){
alert("AA: hello!");
};
module.pokeYourFriend = function(){
BB.sayHello();
};
return module;
})(AA || {}, BB);
var BB = (function(module, AA){
module.sayHello = function(){
alert("BB: hello!");
};
module.pokeYourFriend = function(){
AA.sayHello();
};
return module;
})(BB || {}, AA);
> AA.pokeYourFriend();
*TypeError: Cannot call method 'sayHello' of undefined*
上面的失败是因为 BB 在创建 AA 时不存在。
是否有一种模式允许这样做,或者应该禁止相互依赖?
It seems that using the following javascript module pattern, it is not possible to have mutually dependent modules:
var AA = (function(module, BB){
module.sayHello = function(){
alert("AA: hello!");
};
module.pokeYourFriend = function(){
BB.sayHello();
};
return module;
})(AA || {}, BB);
var BB = (function(module, AA){
module.sayHello = function(){
alert("BB: hello!");
};
module.pokeYourFriend = function(){
AA.sayHello();
};
return module;
})(BB || {}, AA);
> AA.pokeYourFriend();
*TypeError: Cannot call method 'sayHello' of undefined*
the above fails because BB does not exist at the time AA is created.
is there a pattern that allows this, or should mutual dependency be forbidden?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AA
和BB
的 RHS 值是函数表达式,按自上而下的顺序(这是 Javascript 中的正常顺序)求值。因此,在定义BB
之前,不能使用BB
。您可以使用“构造函数”来创建这些模块并为其分配名称(“AA”或“BB”),而不是自调用:
The RHS values of
AA
andBB
are function expressions, which are evaluated in top-down order (which is the normal order in Javascript). Therefore, you cannot useBB
beforeBB
has been defined.Instead of self-invoking, you can use a "constructor" that creates these modules and assigns a name to them ("AA", or "BB"):