正确的原型继承

2024-04-06

所以我真的查遍了互联网,发现了许多在 javascript 中设置原型继承的不同方法。

其中一些使用call().
其中一些使用以下语法:var rabbit.prototype = new Animal.
有些在更改原型后更改构造函数,有些则不更改。
有些设置了一些有助于设置继承的小功能。

有人可以解释一下吗?有很多关于此的帖子,但好的帖子已经有 2 年多了,它们在我的脑海中引起了很大的混乱。
我想一劳永逸地知道如何在 JavaScript 中正确设置原型继承。

如果简单点就更好了!


实现了几种不同的 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++ 中的工作方式,它们具有更典型的继承结构。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正确的原型继承 的相关文章

随机推荐