方式一: es6 extends 继承
class Parent {
constructor() {
this.age = 100;
}
}
class Sun extends Parent{
constructor() {
super();
this.name = "小明";
}
}
const sun = new Sun();
console.log(sun.age, sun.name);
方式二: 原型继承
function Parent() {
this.age = 100;
}
function Child ( ) {
this.name ="小明";
}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name, child.age);
方式三: 借用构造函数
function Parent() {
this.age = 100;
}
function Child() {
// 这个就是 借用构造函数 的精髓
Parent.call(this);
this.name = "小明";
}
const child = new Child();
console.log(child.name, child.age);
方式四: 组合式继承
function Parent() {
this.age = 100;
}
function Child() {
// 继续借用构造函数
Parent.call(this);
this.name = "小明";
}
// 再来一个原型继承, 组合起来,就叫 组合式继承
Child.prototype = new Parent();
const child = new Child();
console.log(child.name, child.age);
面试的时候简单说这些就够了