看起来好像我终于理解了JavaScript继承以及它应该如何正确完成。这里是我的代码:JavaScript和原型继承
function Human(eyes) {
this.eyes = eyes ? "Not blind" : "Blind";
}
Human.prototype.canSee = function() {
return this.eyes;
};
function Male(name, eyes) {
Human.call(this, eyes);
this.name = name;
}
Male.prototype = Object.create(Human.prototype);
var Sethen = new Male("Sethen", true);
console.log(Sethen.canSee()); //logs "Not blind"
据我了解,使用Object.create
创建继承原型对象比使用new
关键字好得多。这在我的脑海里提出了一些问题。
- 在
Male.prototype = Object.create(Human.prototype)
原型链是Male.prototype --> Human.prototype --> Object.prototype --> null
? - 在
Male
构造函数中,我使用Human.call(this, eyes);
来调用一个超类,我不得不在Male
构造函数中再次传递给Human
构造函数。这看起来很痛苦,有没有更简单的方法来做到这一点? - 为什么我有时会看到像
Male.prototype = new Human();
这样的代码......这似乎是不正确的。当我们这样做时究竟发生了什么?
你见过这个http://stackoverflow.com/questions/13040684/javascript-inheritance-object-create-vs-new和这个http://stackoverflow.com/问题/ 4166616 /谅解 - 差异 - 对象 - 创建和新 - somefunction-in-j ??? – rafaelcastrocouto
不,我没有。我会看看。 – Sethen