正确的原型继承 [英] Proper Prototypal Inheritance
问题描述
因此,我确实在Internet上四处张望,并发现了许多不同的方法来设置JavaScript中的原型继承.
So I really looked all over the internet and found many different ways on setting prototypal inheritance in javascript.
其中一些使用call()
.
其中一些使用此语法:var rabbit.prototype = new Animal
.
其中有些更改原型后更改了构造函数,有些则没有.
有些人设置了一个小功能来帮助设置继承.
Some of them use call()
.
Some of them use this sytnax: var rabbit.prototype = new Animal
.
Some of them change the constructor after changing the prototype, some do not.
Some set a little function which helps set inheritance.
请问有人可以阐明这一点吗?关于此的文章很多,但是好的文章已经有2年多的历史了,它们在我的脑海中引起了很大的混乱.
我想一劳永逸地知道如何在javascript中正确地设置原型继承.
Could someone please shed some light on this? There are many posts about this but the good ones are 2+ years old and they've caused a great deal of confusion in my mind.
I would like to know, once and for all, how to actually PROPERLY set prototypal inheritance in javascript.
简单就更好了!
推荐答案
已经实现了几种不同的javascript继承方式,这最终就是我想要为浏览器rpg构造javascript游戏引擎时所要遵循的:
Having implemented several different ways of javascript inheritance this is ultimately what I went with when I wanted to construct a javascript game engine for a browser rpg:
玩家基础类:
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;
最后我们创建一个播放器:
And finally we create a player:
current_player = new Mage(name,type,gender,0,avatar);
现在允许我们执行以下操作:
Which allows us to do this now:
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 ++中的工作方式,它们具有更典型的继承结构.
As others have mentioned there is no best practice in javascript inheritance. I have found the above most closely imitates how you would expect inheritance to work in Java or C++, which have more typical inheritance structures.
这篇关于正确的原型继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!