2012-09-27 48 views
2

我遇到了使用RequireJS和Prototypal繼承的問題。這裏是我的模塊:RequireJS和Prototypal Inheritance

define(function() { 
    function Module(data) { 
    this.data = data; 
    } 

    Module.prototype.getData = function() { 
    return this.data; 
    }; 

    Module.prototype.doSomething = function() { 
    console.log(this.data); 
    console.log(this.getData()); 
    }; 

    return Module; 

    Module.prototype.callFunction = function (fn) { 
    if (this[fn]) { 
     console.log('call'); 
     Module.prototype[fn](); 
    } 
    }; 
}); 

然後,我實例化模塊,像這樣:

var module = new Module({ name: 'Marty' }); 
module.getData(); // returns { name: 'Marty' } 
module.data; // returns { name: 'Marty' } 
module.callFunction('doSomething') // returns undefined on the first (and second) console log 

console.log S IN的module.doSomething()總是返回undefined。我誤解了原型繼承與RequireJS的工作原理嗎?

+0

感謝您發佈您的解決方案。你是否將你的實例化代碼封裝在require()中?當我嘗試你的方法並在require()中包裝最後一個塊時,我得到'模塊未定義'錯誤。 – cantera

+0

是的,它在require()中或者在另一個AMD模塊中被實例化,如下所示:define(['module-file-from-my-example-above'],function(){/ * .. instantiate here */});此外,請確保您的AMD模塊中的return語句是關閉之前的最後一個'});'。不知道我是如何設法錯誤輸入的。如果您在HTML中包含AMD模塊需要幫助,http://requirejs.org/docs/start.html是一個很好的開始。 –

+0

它的工作!非常感謝 - 這對我有很大的幫助。一旦Stack允許,我會盡快獎勵你的賞金點數。再次感謝 – cantera

回答

2

事實證明,我寫了callFunction方法不正確。正確的方法是:

Module.prototype.callFunction = function (fn) { 
    if (this[fn] && typeof this[fn] === "function") { 
    this[fn](); 
    } 
}; 

的問題是使用Module.prototype代替this。哎呦。