实现了几种不同的 JavaScript 继承方式后,当我想为浏览器角色扮演游戏构建 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++ 中的工作方式,它们具有更典型的继承结构。