【发布时间】:2015-03-19 16:29:01
【问题描述】:
我一直在研究 JavaScript 中每个“类”中的“私有”变量的多层次继承,但遇到了这个奇特的奇点:
function Ammo() {
var a = 0;
this.get_ammo = function() {
return a;
};
this.add_to_ammo = function() {
a = a+1
return a;
};
this.clean_ammo = function() {
return a=0;
}
}
function Weapon() {
var a =0;
}
function Gun() {
var a = 0;
this.fire = function(){
console.log("Bang");
}
}
Weapon.prototype = new Ammo();
Weapon.prototype.constructor = Weapon();
Gun.prototype = new Weapon();
Gun.prototype.constructor = Gun();
var a = new Ammo();
var w = new Weapon();
var g = new Gun();
a.add_to_ammo()
a.add_to_ammo()
a.add_to_ammo()
console.log(w.get_ammo())
// At this point I get 0, as expected. But after
w.add_to_ammo()
w.add_to_ammo()
w.add_to_ammo()
console.log(g.get_ammo())
// But here I get 3!
谁能解释一下为什么我得到 3 之后
console.log(g.get_ammo())
我认为对象 a、w、g 是独立的,它们的域也是如此。
我还发现如果我改变了
var a = 0;
到
this.a = 0;
我得到了预期的结果。对象的字段未绑定到其父字段。
【问题讨论】:
标签: javascript inheritance prototype