supertype
构造函数继承其prototype
对象的构造函数仍然可以拥有自己的方法。例如, Bird
是一个从Animal
继承其prototype
的构造函数: function Animal(){}除了从
Animal.prototype.eat = function(){
console.log(“nom nom nom”);
};
函数Bird(){}
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
Animal
继承的内容之外,您还希望添加Bird
对象独有的行为。在这里, Bird
将获得一个fly()
函数。函数以与任何构造函数相同的方式添加到Bird's
prototype
: Bird.prototype.fly = function(){现在
console.log(“我在飞!”);
};
Bird
实例将同时使用eat()
和fly()
方法: let duck = new Bird();
duck.eat(); //打印“nom nom nom”
duck.fly(); //打印“我在飞!”
Dog
对象继承自Animal
, Dog's
prototype
构造函数设置为Dog。然后将一个bark()
方法添加到Dog
对象,以便beagle
可以eat()
和bark()
。 bark()
方法应该打印“Woof!”到控制台。 Animal
不应该响应bark()
方法。
testString: assert(typeof Animal.prototype.bark == "undefined");
- text: Dog
应该继承Animal
的eat()
方法。
testString: assert(typeof Dog.prototype.eat == "function");
- text: Dog
应该将bark()
方法作为own
属性。
testString: assert(Dog.prototype.hasOwnProperty('bark'));
- text: beagle
应该是Animal
一个instanceof
。
testString: assert(beagle instanceof Animal);
- text: beagle
的构造函数应该设置为Dog
。
testString: assert(beagle.constructor === Dog);
```