非常简单的问题
我正在尝试了解javascript中的继承
function Animal() {
this.eats = true;
}
function Rabbit() {
this.jumps = true;
}
//Rabbit is-a Animal
Rabbit.prototype = Animal; //I'm assuming this does not inherit
alert(Rabbit.prototype.eats); // returns undefined
什么是正确的方法?
答案 0 :(得分:7)
这是"回答"但请允许我为子孙后代提供替代方案。
调用父级构造函数来获取父级原型并不是一个好主意。这样做可能会产生副作用;设置id,跟踪实例数,无论构造函数内发生什么。
您可以在Child构造函数和Object.create或polyfill中使用Parent.call()来获取其原型:
function Animal () {
this.eats = true;
}
function Rabbit (legs) {
Animal.call(this);
this.jumps = true;
}
Rabbit.prototype = Object.create(Animal.prototype);
// Or if you're not working with ES5 (this function not optimized for re-use):
Rabbit.prototype = (function () {
function F () {};
F.prototype = Animal.prototype;
return new F();
}());
var bugs = new Rabbit();
alert(bugs instanceof Animal); // true
alert(bugs.eats); // true