我们需要实现如下需求:
function Parent(){}Parent.prototype.name = '父name'function Child(){}Child.prototype.age = '子age'const childInstance = new Child()// 存在父类和子类,子类的实例要同时拥有两个类的原型上的属性和方法。childInstance.name === '父name'childInstance.age === '子age'
ES6 class 继承
先熟悉一下 class 语法:
class Person {constructor() {// 添加到 this 的所有内容都会存在于不同的实例上this.locate = () => console.log("instance", this);}// 定义在类的原型对象上locate() {console.log("prototype", this);}// 定义在类本身上static locate() {console.log("class", this);}}
使用 class 继承:
// 1. 创建父类class Parent {constructor(name) {this.name = name}eat(food) {console.log(`${this.name}正在吃:${food}`)}}// 2. 创建子类 - 继承class Child extends Parent {constructor(name, age) {super(name)this.age = age}intro() {console.log(`${this.name}今年${this.age}岁了`)}}const child = new Child('小明', 16)child.eat('牛肉')child.intro()
