prototype对象从另一个对象继承其行为(方法): ChildObject.prototype = Object.create(ParentObject.prototype);然后,
ChildObject通过将它们链接到其prototype ChildObject获得自己的方法: ChildObject.prototype.methodName = function(){...};可以覆盖继承的方法。它以相同的方式完成 - 通过使用与要覆盖的方法名称相同的方法名称向
ChildObject.prototype添加方法。以下是Bird重写从Animal继承的eat()方法的示例: function Animal(){}如果你有一个实例,请
Animal.prototype.eat = function(){
返回“nom nom nom”;
};
函数Bird(){}
//继承Animal的所有方法
Bird.prototype = Object.create(Animal.prototype);
// Bird.eat()重写Animal.eat()
Bird.prototype.eat = function(){
返回“peck peck peck”;
};
let duck = new Bird();你调用duck.eat() ,这就是JavaScript在duck's prototype链上寻找方法的方法: duck.eat() =>这里定义了eat()吗? No. 2. Bird =>这里定义了eat()吗? =>是的。执行它并停止搜索。 3. Animal => eat()也被定义,但JavaScript在达到此级别之前停止搜索。 4. Object => JavaScript在达到此级别之前停止搜索。 Penguin的fly()方法,使其返回“唉,这是一只不会飞的鸟”。 penguin.fly()应该返回字符串“唉,这是一只不会飞的鸟”。
testString: 'assert(penguin.fly() === "Alas, this is a flightless bird.", "penguin.fly() should return the string "Alas, this is a flightless bird."");'
- text: bird.fly()方法应该返回“我正在飞行!”
testString: 'assert((new Bird()).fly() === "I am flying!", "The bird.fly() method should return "I am flying!"");'
```