我有以下内容:
mod.a = (function() {
var myPrivateVar = 'a';
function myPrivateFct() {
//do something I will need in my sub-module (mod.a.b)
}
return {
//some public functions
}
})();
mod.a.b = (function() {
// some local vars and functions
return {
mySubModuleFct:function() {
// here I want to call mod.a.myPrivateFct();
}
})();
我想创建一个子模块,并从我的父模块mod.a调用一个私有函数。如何在遵循模块模式的最佳实践的同时执行此操作?
答案 0 :(得分:2)
一位同事告诉我该怎么做。它实际上非常优雅。
mod.a = (function() {
var myPrivateVar = 'a';
function myPrivateFct() {
//do something I will need in my sub-module (mod.a.b)
}
return {
b: {
bPublicMethod:function() {
myPrivateFct(); // this will work!
}
}
//some public functions
}
})();
//call like this
mod.a.b.bPublicMethod(); // will call a.myPrivateFct();
答案 1 :(得分:1)
我建议使用 John Resig的简单继承代码来实现更加面向对象的javascript方法:
http://ejohn.org/blog/simple-javascript-inheritance/
它允许你写这个:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
}
});
var Ninja = Person.extend({
init: function(){
this._super( false );
}
});
var p = new Person(true);
p.dancing; // => true
var n = new Ninja();
n.dancing; // => false