2012-03-05 78 views
0

我新的Javascript功能來OOP和只需要得到與此交手。的Javascript實例子類與父屬性

如果我有一個特性

function myClass(){ 
this.foo=null; 
} 

然後我用繼承來創建一個子類

myChild.prototype = new myClass(); 

function myChild(){ 
alert(this.foo); 
} 

如何實例子類如我希望當我設置foo的屬性的類提醒'酒吧'。我不想簡單地傳遞「酒吧」到myChild因爲我有相關的MyClass中的方法,而不是myChild屬性來設置的列表。

var newChild = new myChild(); 
+0

你的第一個片段缺失'()',如果你想字符串'bar'那麼你需要引用它。 – pimvdb 2012-03-05 14:25:24

+0

編輯,修復錯誤 – user1209203 2012-03-05 14:26:13

+0

我不知道,你想通過'「酒吧」'。哪個功能應該接受並設置它?該子類應設置它,但你不希望它傳遞到子類 - 你能否詳細說明嗎? – pimvdb 2012-03-05 14:28:06

回答

0

實際上,你可以找到這個問題的答案也in my answer to previous question,它類似於其它語言的繼承。

如果擴展一個類,子類的構造函數必須接受它自己的參數父類的參數。因此,假如您有:

function Parent(a) { 
    this.foo = a; 
}; 

// and 

function Child(b, a) { 
    Parent.call(this, a); // executes the parent constructor for this instance 
    this.bar = b; 
    alert(this.foo); 
}; 

inherits(Parent, Child); 

(的inherits實現可以在this answer找到)。

裏面Child你必須調用父類的construtor和傳遞的參數,類似於你如何在Java或Python這樣做。

如果你有很多的參數,那麼你可以使用arguments對象,使事情變得更簡單:

function Parent(a, b, c, d) {...}; 

function Child(e, f) { 
    // c and d are parameters for `Child` 
    // arguments[0] == e 
    // arguments[1] == f 
    // all other arguments are passed to Parent, the following 
    // creates a sub array arguments[2..n] 
    Parent.apply(this, [].slice.call(arguments, 2); 
    /... 
} 

// later 

var child = new Child(e, f, a, b, c, d); 

一般來說,myChild.prototype = new myClass();是不是一個很好的遺傳模式,因爲大多數的時間,班級期待一些論點。這不會爲每個實例執行父構造函數,而只對所有實例執行一次。

+0

謝謝felix接受答案,因爲它回答我的問題,但我意識到我可以做到這一點更簡單的實例化對象的一些參數,然後調用帶有額外參數的方法新線,而不是試圖一口氣做到這一切。 – user1209203 2012-03-05 17:32:13

0

你可以只設置屬性在孩子的構造,像這樣:

myChild.prototype = new myClass(); 

function myChild(){ 
    this.foo = "bar"; 
} 

這是你想要的嗎?

或者,如果你想成爲靈活什麼foo包含在每一種情況下,你可以設置它的子類的實例化後右:

var child = new myChild(); 
child.foo = "bar"; 
0

參數化的施工方法。

function myClass(foo){ 
    this.foo=foo; 
} 
myChild.prototype = new myClass('bar'); 

function myChild(){ 
    alert(this.foo); 
} 
var newChild = new myChild(); 

或:

function myClass(){ 
     this.foo=null; 
    } 
    myChild.prototype = new myClass(); 
    myChild.prototype.foo = 'bar'; 
    function myChild(){ 
     alert(this.foo); 
    } 
    var newChild = new myChild(); 
+0

我不能做到這一點,因爲每個對象都會得到不同的值 – user1209203 2012-03-05 14:38:53

+0

這是你想要的嗎? 'myChild.prototype.foo ='bar';' – 2012-03-05 14:43:13