如何用class实现继承
class用法
class Student {constructor(name, number) {this.name = namethis.number = number// this.gender = 'male'}sayHi() {console.log(`姓名 ${this.name} ,学号 ${this.number}`)// console.log(// '姓名 ' + this.name + ' ,学号 ' + this.number// )}// study() {// }}// 通过类 new 对象/实例const xialuo = new Student('夏洛', 100)console.log(xialuo.name)console.log(xialuo.number)xialuo.sayHi()const madongmei = new Student('马冬梅', 101)console.log(madongmei.name)console.log(madongmei.number)madongmei.sayHi()
继承
- class 的继承方式,包括属性和方法
- extends 继承自….
- super 调用父类构造函数,传递父类的值,避免一处多改
// 父类class People {constructor(name) {this.name = name}eat() {console.log(`${this.name} eat something`)}}// 子类class Student extends People {constructor(name, number) {super(name)this.number = number}sayHi() {console.log(`姓名 ${this.name} 学号 ${this.number}`)}}// 子类class Teacher extends People {constructor(name, major) {super(name)this.major = major}teach() {console.log(`${this.name} 教授 ${this.major}`)}}// 实例const xialuo = new Student('夏洛', 100)console.log(xialuo.name)console.log(xialuo.number)xialuo.sayHi()xialuo.eat()// 实例const wanglaoshi = new Teacher('王老师', '语文')console.log(wanglaoshi.name)console.log(wanglaoshi.major)wanglaoshi.teach()wanglaoshi.eat()
隐式原型和显示原型
instanceof
可以判断具体引用类型,也可以说是可以判断前面的变量是不是被后面的class或者其子类构建出来的。
- 可以理解为:xialuo.proto===student.prototype
- xialuo.proto.prototype===people.prototype

原型
- class实际是函数,可见是语法糖。

- _proto:隐式原型;prototype:显示原型。二者全等(===)

- 每个class都有显示原型prototype,每个实例都有隐式原型proto,实例的proto指向对应class的prototype

- 基于原型的执行规则
原型链(重要)


此处要注意,name是xialuo本身的属性,但sayHi不是。如:
hasOwnprototype是Object.prototype中的。故
面试题
如何准确判断一个变量是不是数组
手写一个简易的jQuery,考虑插件和扩展性
class的原型本质,怎么理解?

