从超类继承行为
在上一个挑战中,我们创建了一个Animal
超类(supertype
),用来定义所有动物共有的行为:
function Animal() { }
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
在这一节以及下一节挑战中我们将学习如何在 Bird
和 Dog
中重用 Animal
中的方法,而无需重新定义它们。 这里我们会用到构造函数的继承特性。 这一节挑战中我们学习第一步:创建一个超类 supertype
(或者叫父类)的实例。 你已经学会了一种创建 Animal
实例的方法,即使用 new
操作符:
let animal = new Animal();
此语法用于继承时会存在一些缺点,这些缺点对于当前我们这个挑战来说太复杂了。 相反,我们学习另外一种没有这些缺点的方法来替代 new 操作:
let animal = Object.create(Animal.prototype);
Object.create(obj)
创建了一个新对象,并指定了 obj
作为新对象的 prototype
。 回忆一下,