我一直在研究有關「私有」變量繼承多個leveles在JavaScript中每一個「類」,但碰上這種奇特的奇點:的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;
我得到預期的結果。對象的領域與他們的父母領域沒有任何聯繫。