在实现了几种不同的 javascript 继承方式之后,当我想为浏览器 rpg 构建一个 javascript 游戏引擎时,这最终是我所采用的:
播放器基类:
function Player(name, type, gender, experience, avatar){
this.name = name;
this.type = type;
this.gender = gender;
this.experience = experience;
this.avatar = avatar;
this.stats ={//getter, setter}
//lots more code
}
向播放器类添加方法
Player.prototype.decrease_life = function(decrement){}
//note that the keyword this in the decrease_life function will
//refer to the player that the method is called on.
现在播放器类的继承:
function Mage(name, type, gender, exp, avatar){
Player.apply(this, [name,type,gender,exp,avatar]);
//apply allows you to specify what the keyword
//this refers to in the Player super class.
}
Mage.prototype = new Player;
最后我们创建一个播放器:
current_player = new Mage(name,type,gender,0,avatar);
这使我们现在可以这样做:
current_player.decrease_life(20); //The mage loses 20 life!
或者这样做:
current_player.stats.get();
//returns the mages stats, it does that because we used apply, and
//this.stats in the player class is referring to our mage now
正如其他人所提到的,javascript 继承没有最佳实践。我发现上面最接近地模仿了您期望继承在 Java 或 C++ 中的工作方式,它们具有更典型的继承结构。