javascript中继承的正确语法
非常琐碎的问题 我试图理解javascript中的继承javascript中继承的正确语法,javascript,Javascript,非常琐碎的问题 我试图理解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
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
什么是正确的方法?这是“答案”,但请允许我为后代提供另一种选择
调用父级的构造函数来获取父级的原型不是一个好主意。这样做可能有副作用;设置ID,跟踪实例的数量,不管构造函数内部发生了什么
您可以在子构造函数和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
这是“回答”,但请允许我为后代提供另一种选择
调用父级的构造函数来获取父级的原型不是一个好主意。这样做可能有副作用;设置ID,跟踪实例的数量,不管构造函数内部发生了什么
您可以在子构造函数和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