gpt4 book ai didi

javascript - 适当的原型(prototype)继承

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:35:06 24 4
gpt4 key购买 nike

所以我真的在整个互联网上寻找了很多在 javascript 中设置原型(prototype)继承的不同方法。

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

有人可以解释一下吗?有很多关于这个的帖子,但好的帖子已经有 2 年以上的历史了,它们在我脑海中造成了很大的困惑。
我想一劳永逸地知道如何在 javascript 中真正正确地设置原型(prototype)继承。

越简单越好!

最佳答案

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

关于javascript - 适当的原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16020577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com