javascript中正确的继承语法

Correct syntax for inheritance in javascript

本文关键字:继承 语法 javascript      更新时间:2023-09-26

非常简单的问题

我正在尝试理解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

什么是正确的方式?

这个问题已经回答了,但请允许我为子孙后代提供另一种选择。

调用父类的构造函数来获取父类的原型不是一个好主意。这样做可能会有副作用;设置id,跟踪实例数量,以及构造函数内部发生的任何事情。

可以在Child构造函数和Object中使用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