2015-05-29 43 views
0
> function Parent() {this.arr = [];} 
undefined 
> function Child() {} 
undefined 
> Child.prototype = new Parent(); 
{ arr: [] } 
> child1 = new Child(); 
{} 
> child2 = new Child(); 
{} 
> child1.arr.push('From child1'); 
1 
> child2.arr 
[ 'From child1' ] 
> 

鑑於上述,我期望child2.arr是空的,因爲它是它自己的對象。我如何讓child1和child2包含他們自己的arr?謝謝!繼承的子對象在JavaScript中共享相同的數組屬性?

回答

2

你必須使你的構造函數賦值:

function Child() { 
    this.arr = this.arr ? this.arr.slice(0) : []; 
} 

這給了每個孩子原型的.arr數組的一個副本,如果它存在。 (這只是一個淺拷貝,這只是一個可能的例子。)對象屬性的賦值總是涉及目標對象的本地(「自己」)屬性,但引用涉及原型鏈。

也不是那個相當神祕的原因,初始化這樣的原型並不是一個好主意。最好使用Object.create

Child.prototype = Object.create(Parent.prototype); 

這使你使用了Parent原型對象作爲其原型的新對象。

Here is a somewhat old but still interesting question on the topic.

+0

在子構​​造函數中添加賦值非常棒!謝謝! – hooinator

0
function Parent() { this.arr = []; } 
function Child() { this.parent = new Parent(); } 
Child.prototype = new Parent(); 
var child1 = new Child(); 
var child2 = new Child(); 
child1.parent.arr.push('From child1'); 
alert(child2.parent.arr); 
1

查找到inheritance in javascript

基本上,如果財產是不是你正在尋找到JavaScript對象上看起來到它的原型,並試圖找到它,直到它到達Object

Child沒有財產arr但它的原型new Parent()不和,一個是從Child1Child2簡稱。