【发布时间】:2015-04-13 18:20:31
【问题描述】:
我阅读了很多关于此事的文章,也观看了一些视频。但是,我仍然无法理解哪一个以及为什么比另一个更好 - 经典/功能和原型继承。我在发帖前发现和阅读的内容:
- No ways to have class-based objects in javascript?
- How to "properly" create a custom object in JavaScript?
- http://aaditmshah.github.io/why-prototypal-inheritance-matters
- http://alexsexton.com/blog/2013/04/understanding-javascript-inheritance
- Javascript when to use prototypes
- 还有其他几个,很遗憾,我现在找不到。
我想提一下,我想根据性能、稳定性(容易出错)或其他优点/缺点更好地了解哪种继承类型更好。 我还指出 OOP 和继承不是基于任何库或自定义代码(不包括用于对象创建的 polyfill)。如果使用支持自己的OOP和继承的框架,我会用它,但这里我对那些不感兴趣。
这是我使用原型代码和经典代码编写的一些代码。
var Human = function(name){
this.name = name;
return this;
};
Human.prototype.introduce = function(){
return "I am " + this.name;
};
var Ninja = function(name, level){
Human.call(this, name);
this.level = level;
}
Ninja.prototype = Object.create(Human.prototype);//new Human();
Ninja.prototype.introduce = function(){
var base = Human.prototype.introduce.call(this);
return base + " My level is " + this.level;
};
Ninja.prototype.fight = function(){
return (this.name + " can fight");
};
var MasterNinja = function(name, level, masterClass){
Ninja.call(this, name, level);
this.masterClass = masterClass;
}
MasterNinja.prototype = Object.create(Ninja.prototype);//new Ninja();
MasterNinja.prototype.introduce = function(){
var base = Ninja.prototype.introduce.call(this);
return base + " My master class is " + this.masterClass;
};
MasterNinja.prototype.fight = function(){
var base = Ninja.prototype.fight.call(this);
return base + " have master class!";
};
MasterNinja.prototype.masterFight = function(){
return this.name + " can master fight!";
};
var human = {
_init: function(name){
this.name = name;
return this;
},
introduce: function(){
return ("Hi, I am " + this.name);
}
};
var ninja = Object.create(human);
ninja._init = function(name, level){
human._init.call(this, name);
this.level = level;
return this;
};
ninja.introduce = function(){
var base = human.introduce.call(this);
return base + " My level is " + this.level;
};
ninja.fight = function(){
return (this.name + " can fight");
};
var masterNinja = Object.create(ninja);
masterNinja._init = function(name, level, masterClass){
ninja._init.call(this, name, level);
this.masterClass = masterClass;
return this;
};
masterNinja.introduce = function(){
var base = ninja.introduce.call(this);
return base + " My master class is " + this.masterClass;
};
masterNinja.fight = function(){
var base = ninja.fight.call(this);
return base + " have master class!";
};
masterNinja.masterFight = function(){
return this.name + " can master fight!";
};
我创建了一个 jsperf 测试,可以在这里找到:
http://jsperf.com/js-basic-inheritance
这表明使用'new'比'Object.create'快得多。
我很高兴听到你的想法。我希望这不是不必要的问题,因为我还没有找到答案。如果我在代码中犯了严重错误,请给我反馈。
【问题讨论】:
-
您的切线附加问题已回答here。请每个帖子只问一个问题,我已将其删除。
-
真的没有搜索编辑问题,抱歉。谢谢你的链接!
标签: javascript performance oop inheritance