如果在原型中定義一個成員在一個對象的所有實例中共享一個成員,那麼是否更改該成員的值也會爲所有對象更改它?在原型中定義的值是否共享?
var A = function() {};
A.prototype.value = 1;
A.prototype.getValue = function() {
return this.value;
};
var B = function() {};
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
var a = new A();
document.writeln("a constructor is A = " + (a.constructor === A) + "<br>");
document.writeln("a.value = " + a.value + "<br>");
document.writeln("a.getValue() = " + a.getValue() + "<br>");
a.value += 1;
document.writeln("a.value = " + a.value + "<br>");
document.writeln("a.getValue() = " + a.getValue() + "<br>");
var b = new B();
document.writeln("b constructor is B = " + (b.constructor === B) + "<br>");
document.writeln("b.value = " + b.value + "<br>");
document.writeln("b.getValue() = " + b.getValue() + "<br>");
b.value += 1;
document.writeln("b.value = " + b.value + "<br>");
document.writeln("b.getValue() = " + b.getValue() + "<br>");
var bb = new B();
document.writeln("bb constructor is B = " + (bb.constructor === B) + "<br>");
document.writeln("bb.value = " + bb.value + "<br>");
document.writeln("bb.getValue() = " + bb.getValue() + "<br>");
bb.value += 1;
document.writeln("bb.value = " + bb.value + "<br>");
document.writeln("bb.getValue() = " + bb.getValue() + "<br>");
結果我得到的是:
a constructor is A = true
a.value = 1
a.getValue() = 1
a.value = 2
a.getValue() = 2
b constructor is B = true
b.value = 1
b.getValue() = 1
b.value = 2
b.getValue() = 2
bb constructor is B = true
bb.value = 1
bb.getValue() = 1
bb.value = 2
bb.getValue() = 2
這是我一直在使用這種嘗試一個普拉克。 http://plnkr.co/edit/znckausaYi9cQ2glJg1A
如果值是在原型,爲什麼B和BB似乎有一些有價值的單獨的實例?我預期的BB,結果是這樣的:
bb constructor is B = true
bb.value = 2
bb.getValue() = 2
bb.value = 3
bb.getValue() = 3
問題:
- 這是爲什麼表現如此?
- 有沒有辦法來驗證原型的成員的位置?
- 是否有一個工具,我可以用它來證明成員跨實例共享與每個實例的一員?