2014-02-13 33 views
0

我希望用戶能夠通過給定對象字面量的一個函數從基類和其他用戶創建的類創建類。與父變量的javascript繼承

所以會有類的列表:

var allclasses = {}; 

父類可以是這個樣子,所有的類有這樣的祖先: 基地=函數(){ this.name =「基地」 ; this.varname = 250; } base.prototype = { foo:function(){ this.varname + = 50; } } // added to allclasses allclasses ['base'] = base;

和方法來創建新類:

function create(childliteral) { ???? } 

的這是如何工作的一個例子,理想:

var myclass = create({ 
    parentname: 'base', // a required variable, create will return false if this isn't valid (not in allclasses) 
    name: 'specialname', // a required variable, create will return false if this is already in allclasses 
    foo: function() { 
    this.varname += 100; 
    // this is the part is what causes the most stress, I want it to call the parents function 'foo' 
    this.parent.foo(); 
    return this.varname; 
    } 
}); 

,然後創建類的實例:

var myobject = new myclass(); 

或......

var myobject2 = new allclasses['specialname']; 

最後,調用

myobject.foo(); 
console.log(myobject.varname) // prints out 400 

myobject.parent.foo(); 
console.log(myobject.varname) // prints out 450 
console.log(myobject.parent.varname) // also prints out 450 
console.log(myobject.parent.name) // prints out 'base' 
console.log(myobject.parentname) // prints out 'base' 
console.log(myobject.name) // prints out 'specialname' 

我已經得到了非常接近這一點,除了我不能比鏈兩個對象多。

+0

向我們展示你當前的代碼,請!請注意,'this.parent。...'會丟失當前實例的上下文,因此您可能需要重新考慮該模式。也可以看一下['Class.js'](http://stackoverflow.com/a/15052240/1048572)以獲得靈感:-) – Bergi

+0

另外,你可以看一下T.J. Crowder的** [Lineage](https://code.google.com/p/lineagejs/)**。但在這裏使用「class」這個詞要謹慎;它經常會帶來其他語言的期望,而這些語言不容易被Javascript的基於原型的繼承以及JS中不存在的那些語言的限制所滿足。此外,許多JS人都對此感到棘手。 :-) –

+0

你需要更好地解釋你想要傳入創建方法的選項 – ppoliani

回答

0

您需要以某種方式存儲對超類的引用;例如

var myclass = create({ 
    parentName: 'Base', 
    name: 'specialname', 
    childCtor: function() { }, 
    childProto: { 
     foo: function(){ 
     this.varname += 100; 
     this._base_.foo(); // reference to the superclass 
     return this.varname; 
     } 
    } 
}); 

看看,這例子http://jsfiddle.net/zzu8J/7/