技术/前端/ECMAScript
class
的继承通过extends
关键词实现,具体继承关系如下图所示:
Animal
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
run(speed) {
this.speed += speed;
alert(`${this.name} runs with speed ${this.speed}.`);
}
stop() {
this.speed = 0;
alert(`${this.name} stands still.`);
}
}
let animal = new Animal("My animal");
Rabbit
class Rabbit {
constructor(name) {
this.name = name;
}
hide() {
alert(`${this.name} hides!`);
}
}
let rabbit = new Rabbit("My rabbit");
可以通过extends
让Rabbit
继承Animal
class Rabbit extends Animal {
hide() {}
}
这样Rabbit
可以继承Animal
的run
和stop
方法。
在内部,extends
会给Rabbit.prototype
增加[[Prototype]],指向Animal.prototype
ES6具体实现是使用Object.setPrototypeOf
方法
Object.setPrototypeOf = function (obj, proto) {
obj.__proto__ = proto;
return obj;
}
实现基础:
// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);
const b = new B();
ES5实现继承:
function Super() {}
function Sub() {}
Sub.prototype = new Super();
Sub.prototype.constructor = Sub;
var sub = new Sub();
ES5实现继承和ES6中的继承基本一致,只有一些不同。ES6中的子类和父类也会通过__proto__
链接。