2012-04-11 53 views
5

我有這個JavaScript:如何包裝構造函數?

var Type = function(name) { 
    this.name = name; 
}; 

var t = new Type(); 

現在我想補充一點:

var wrap = function(cls) { 
    // ... wrap constructor of Type ... 
    this.extraField = 1; 
}; 

所以我可以做:

wrap(Type); 
var t = new Type(); 

assertEquals(1, t.extraField); 

[編輯]我想的實例屬性,而不是類(靜態/共享)屬性。

在包裝函數中執行的代碼應該像我將它粘貼到真正的構造函數中那樣工作。

Type的類型不應該改變。

+1

按照我的理解,你想添加一個額外的屬性給構造函數?以便更多的新實例擁有該屬性? – Joseph 2012-04-11 07:20:29

+0

可能你只需要在'wrap()'函數內改變'Type'的原型。例如:'var wrap = function(cls){cls.prototype.extraField = 1; };'?或者可能最好是用'extraField'成員創建從'Type'繼承的新'Type2'? – 2012-04-11 07:27:54

+0

你能描述一下你的問題嗎? – seteh 2012-04-11 07:28:57

回答

5

更新:An updated version here

你實際上是在尋找被擴展類型到另一個類。在JavaScript中有很多方法可以做到這一點。我不是一個真正的new的粉絲,建設「類」的prototype方法(我更喜歡寄生繼承樣式更好),但這裏是我的了:

//your original class 
var Type = function(name) { 
    this.name = name; 
}; 

//our extend function 
var extend = function(cls) { 

    //which returns a constructor 
    function foo() { 

     //that calls the parent constructor with itself as scope 
     cls.apply(this, arguments) 

     //the additional field 
     this.extraField = 1; 
    } 

    //make the prototype an instance of the old class 
    foo.prototype = Object.create(cls.prototype); 

    return foo; 
}; 

//so lets extend Type into newType 
var newType = extend(Type); 

//create an instance of newType and old Type 
var t = new Type('bar'); 
var n = new newType('foo'); 


console.log(t); 
console.log(t instanceof Type); 
console.log(n); 
console.log(n instanceof newType); 
console.log(n instanceof Type); 
+0

從你的控制檯輸出,我想擴展存儲在'constructor'中的函數。新字段應顯示在「name」旁邊,而不是「constructor」旁邊。 – 2012-04-11 07:31:36

+0

所以你真正想做的是創建另一個構造函數?或者只是添加到現有? – Joseph 2012-04-11 07:38:46

+0

我想擴展現有的構造函數。 – 2012-04-11 07:40:06

0

我不知道該怎麼辦這是你提出的方式,儘管我承認這會讓我感興趣。我只能想到將類型變量重新分配給這樣的包裝函數:

var wrap = function(name) 
{ 
    Type.prototype.constructor.call(this, name); 
    this.extraField = 1; 
}; 
wrap.prototype = Type.prototype; 
Type = wrap; 

var t = new Type(); 
assertEquals(1, t.extraField); 
相關問題