2010-08-16 60 views
2
function A(){ 
    this.a = {}; 
    this.b = 0; 
    this.Test = function(value){ 
     this.a.x = value; 
     this.b = value; 
    }; 
} 

function B(){} 
B.prototype = new A; 


    var b1= (new B()); 
    b1.Test(1); 
    var b2= (new B()); 
    b2.Test(2); 
    log(b1.b == 1); //true 
    log(b2.b == 2); //true 
    log(b1.a.x == 1);//false x == 2 
    log(b2.a.x == 2);//true 

爲什麼實例共享字段a?JavaScript字段繼承奇怪行爲

回答

2

發生這種情況的原因是a對象在B的所有實例中共享(因爲B原型的實例是A的實例)。

一種解決方法是在你的Test方法分配一個新的對象作爲自己的財產陰影的一個可用的原型鏈,例如:

function A(){ 
    this.a = {}; 
    this.b = 0; 
    this.Test = function(value){ 
    this.a = {x: value}; // shadow the object on the prototype chain 
    this.b = value; 
    }; 
} 

function B(){} 
B.prototype = new A; 


var b1= new B(); 
b1.Test(1); 

var b2= new B(); 
b2.Test(2); 

console.log(b1.b == 1); //true 
console.log(b2.b == 2); //true 
console.log(b1.a.x == 1);//true 
console.log(b2.a.x == 2);//true 
+0

>這是因爲一個對象在B的所有實例中共享。 但爲什麼它與b字段一起工作?爲什麼對象是共享的,但簡單類型不是? – dotneter 2010-08-16 17:48:01

+0

@dotneter:'a'是一個對象,通過做:'this.ax = value;'你正在修改繼承對象,被所有實例共享,通過賦值this.b = value;'你正在創建一個屬性在當前對象('this')中隱藏繼承的對象,就像在我的例子中一樣'this.a = {x:value};',在this指向的對象上創建一個新屬性。 – CMS 2010-08-16 19:09:14