0
我想了解我在此fiddle中重新創建的行爲。爲什麼我的基類的對象屬性與所有子類的實例共享?
function BaseObject(){}
BaseObject.prototype.value = 1;
BaseObject.prototype.obj = {value:1};
BaseObject.prototype.log = function() {
console.log(this.constructor.name + " - Value: " + this.value);
console.log(this.constructor.name + " - ObjValue: " + this.obj.value);
};
BaseObject.prototype.add = function(i) {
this.value += i;
this.obj.value += i;
};
function Derivation1(){}
Derivation1.prototype = Object.create(BaseObject.prototype);
Derivation1.prototype.constructor = Derivation1;
function Derivation2(){}
Derivation2.prototype = Object.create(BaseObject.prototype);
Derivation2.prototype.constructor = Derivation2;
var first = new Derivation1();
var second = new Derivation2();
first.log();
first.add(1);
first.log();
second.log();
輸出爲:
Derivation1 - Value: 1
Derivation1 - ObjValue: 1
Derivation1 - Value: 2 <-- as expected
Derivation1 - ObjValue: 2 <-- as expected
Derivation2 - Value: 1
Derivation2 - ObjValue: 2 <-- Why is this two too and not 1?
的行爲表明,該對象的成員獲得由所有實例共享或靜態的方式進行訪問,而每個原始成員居住在自己的實例。
難道有人會對此有所瞭解嗎?
所有內容都是按值共享的,而BaseObject.prototype.obj的值是對對象的引用。所以所有的實例都會引用同一個對象。 – Shilly