JavaScript中的面向对象

75 阅读1分钟

本质是原型链的形式实现面向对象,这种设计模式为 原型模式

ES6之前的面向对象

function Person(name,age){
	this.name = name;
 this.age = age;
}
Person.prototype.say(){
  console.log(`${this.name}的年龄是${this.age}`);
}
function Student(name,age){
  // 通过call将当前this指向父类 获取到父类的声明属性
  Person.call(this,name,age);  //借用构造函数继承
  // 以下代码重复,违反了 DRY原则 可被提取到父类中
  // this.name = name;
  // this.age = age;
}
// 当前子类的原型对象指向父类的实例对象 获取到 父类原型对象上的方法
Student.prototype = new Person(); //原型继承
// 将constructor重新指回自己 
Student.prototype.constructor = Student;
//原型继承+借用继承 可实现属性和方法的继承 俗称组合式继承

ES6之后的面向对象

class Person{
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
  say(){
    console.log(`${this.name}的年龄是${this.age}`);
  }
}

// 子类通过extends关键字继承父类 继承父类的方法
class Student extends Person{
  constructor(name,age,stuId){
    // super关键字必须放在construcotr的第一句,通过`super`继承父类的属性
    super(name,age);
  }
  // 继承父类的方法进行重写 overwrite 实现多态 
  say(){
      console.log(`${this.name}的年龄是${this.age},学号是${this.stuId}`);
  }
}