说明
在之前的课程中,你了解到一个对象可以通过克隆其prototype
对象来继承其他对象的行为(方法):
ChildObject.prototype = Object.create(ParentObject.prototype);
然后,ChildObject
通过将它们链接到其prototype
来接收自己的方法:
ChildObject.prototype.methodName = function() {...};
可以覆盖继承的方法。它的工作方式相同 - 通过使用与要覆盖的方法名称相同的方法名称,向ChildObject.prototype
添加一个方法。
以下是Bird
覆盖从Animal
继承的eat()
方法的示例:
function Animal() { }
Animal.prototype.eat = function() {
return "nom nom nom";
};
function Bird() { }
// 继承自Animal的所有方法
Bird.prototype = Object.create(Animal.prototype);
// Bird.eat()覆盖Animal.eat()
Bird.prototype.eat = function() {
return "peck peck peck";
};
如果你有一个实例 var duck = new Bird();
,你调用duck.eat()
,这就是JavaScript如何查找在duck
的原型链上的方法的途径:
1.duck => Is eat()这里是否定义?没有。
2.Bird => Is eat()这里是否定义? =>是的。执行它并停止搜索。
3.Animal => eat()也被定义,但JavaScript在达到此级别之前停止搜索。
4.Object => JavaScript在达到此级别之前停止搜索。
练习
覆盖Penguin
的fly()
方法,以使它返回“Alas, this is a flightless bird.”。
penguin.fly()
应该返回字符串"Alas, this is a flightless bird."。bird.fly()
方法应该返回 "I am flying!"
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
// Add your code below this line
// Add your code above this line
var penguin = new Penguin();
console.log(penguin.fly());
答案
方法 | 描述 |
function() | 是一个可以被其他代码或其自身调用的代码片段,或者是一个指向该函数的变量 。 |
Javascript构造函数 | 函数名第一个字母大写。 |
prototype | 给对象添加属性和方法。 |
console.log() | 用于在控制台输出信息(浏览器按下 F12 打开控制台)。 |
Object | 构造函数创建一个对象包装器。 |
Object.create() | 创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。 |
constructor | 返回对创建此对象的数组函数的引用。 |
() => | 箭头函数表达式更适用于那些本来需要匿名函数的地方,并且它不能用作构造函数。 |
var | 声明一个变量,并可选地将其初始化为一个值。 |
new | 创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。 |
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
// Add your code below this line
Penguin.prototype.fly = () => "Alas, this is a flightless bird."
// Add your code above this line
var penguin = new Penguin();
console.log(penguin.fly());
运行结果