使用构造函数显示模块模式

时间:2013-08-22 12:44:01

标签: javascript revealing-module-pattern

我在找出实现这一目标的最佳方法时遇到了一些麻烦。

我想要一个具有构造函数的模块,该构造函数接受一个存储它的参数,以便以后在模块中使用。

var ModuleB = function(moduleA) {
    this.moduleA = moduleA;
}

ModuleB.prototype = function() {
    //private stuff/functions
    function someMethod() {
        moduleA.doSomething();
    }

    //public api
    return {
        someMethod : someMethod
    };
}();

在其他一些文件中

//ModuleA defined elsewhere
var moduleA = new ModuleA();

//...

var module = new ModuleB(moduleA);
module.someMethod();

现在在someMethod上面,moduleA未定义,this是全局窗口对象。有人可以解释我如何访问moduleA吗?我不明白构造函数后this.moduleA = moduleA;会发生什么。我不是一个真正的JavaScript开发人员,所以如果我在这里或其他地方使用错误的模式,请随意加入。

3 个答案:

答案 0 :(得分:10)

你非常亲密,但是你在someMethod的定义中遗漏了一些重要内容。

编辑:如果更改ModuleB中模块属性的名称,则更容易分辨哪些有用,哪些无效:

var ModuleA = function() {}

ModuleA.prototype = (function () {
    return {
        someMethod: function () {
            return 'foo';
        }
    };
}());

var ModuleB = function(moduleA) {
    this.innerModule = moduleA;
}

ModuleB.prototype = (function () {
    return {
        doStuff: function () {
            return this.innerModule.someMethod();
        }
    };
}());

var moduleA = new ModuleA();

var moduleB = new ModuleB(moduleA);
console.log(moduleB.doStuff()); // prints "foo"

http://jsfiddle.net/mN8ae/1/

答案 1 :(得分:1)

试试这个:

var ModuleB = function(moduleA) {
    this.moduleA = moduleA;
}

// Simplifying your code, what was missin is the "this" keyword accessing the moduleA
ModuleB.prototype.someMethod = function() {       
   this.moduleA.doSomething();
};


var module1 = new ModuleB({ 
    doSomething: function(){ 
         alert('i do something'); 
    } 
});

module1.someMethod();

答案 2 :(得分:0)

您需要使用call / apply来执行给定上下文的方法。

试试这段代码(我修改了你的代码)

var ModuleB = function(moduleA) {
     this.moduleA = moduleA;
      };

 ModuleB.prototype = function() {
     //private stuff/functions
     function someMethod() {

         this.doSomething();
     }

     //public api
     return {
         someMethod : someMethod
     }; }();


 var ModuleA=function(){
     this.doSomething=function(){
      alert('moduleA Method');   
     }; };

 var modA=new ModuleA(); var modB=new ModuleB(modA);
 modB.someMethod.call(modA);

谢谢!

相关问题