【发布时间】:2015-05-03 01:02:46
【问题描述】:
var Main = function(){};
Main.prototype = {
'times' : 0,
'request': function(){},
...
};
var SubA = function(){};
SubA.prototype = new Main() // same with Object.create(Main.prototype);
SubA.prototype.constructor = SubA;
var SubB = function(){};
SubB.prototype = new Main() // same with Object.create(Main.prototype);
SubB.prototype.constructor = SubB;
现在:
var sub_a = new SubA();
sub_a.times = 1;
var sub_b = new SubB();
// Here sub_b.times is already 1, how?
当我改变sub类的属性时,Main的属性也在改变,不应该停留在0吗?
【问题讨论】:
-
仅使用 Chrome 控制台对我来说它保持在 0?
-
sub_a.times = 1;永远不会 (!) 更改sub_b.times,除非sub_a === sub_b。这与原型无关。 分配到属性总是添加或更改对象本身的属性(无论它是否存在于原型链中)。
标签: javascript inheritance prototype prototypal-inheritance