extends 关键字允许您继承现有对象。例如,假设您有一个 Animal 对象:
fn Animal(name) {
this.name = name;
this.walk = fn() {
console.log('\(name) is walking...');
};
}
Animal.prototype.getLegs = fn() {
return 4;
};
您现在可以使用 extends 关键字创建另一个继承 Animal 的对象:
fn Spider(name)
extends Animal(name) {
}
Spider.prototype.getLegs = fn() {
return 8;
};
当您创建一个新的Spider 对象时,您将自动拥有您的walk 方法,因为Spider 扩展了Animal。
var spider = new Spider("Skitter the Spider");
spider.walk();
Spider(语言)还提供了super 关键字,可以让您轻松访问您正在扩展的对象。例如:
Spider.prototype.getLegs = fn() {
return super.getLegs() + 4;
};
spider.getLegs(); // => 8
实施
Spider 中的这段代码:
fn Spider() extends Animal {}
编译为以下 JavaScript:
function Spider() {
Animal.call(this);
}
Spider.prototype = Object.create(Animal);