继承模式

原型继承

子类型的原型为父类型的一个实例对象

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.setName = function (name) {
  this.name = name;
}
function Student (name, age, grade) {
  Person.call(this, name, age);
  this.grade = grade;
}
// 子类型的原型为父类型的一个实例对象
function F () {}
F.prototype = Person.prototype;
Student.prototype = new F();
// 修复子类型的 constructor 指向
Student.prototype.constructor = Student;
Student.prototype.setGrade = function (grade) {
  this.grade = grade;
}
var st1 = new Student('aaa', 18, 88);
console.log(st1); // Student { name: 'aaa', age: 18, grade: 88 }
st1.setGrade(90);
st1.setName('bbb');
console.log(st1); // Student { name: 'bbb', age: 18, grade: 90 }

继承封装

function inherit(Target, Origin) {
  function F() {};
  F.prototype = Origin.prototype;
  Target.prototype = new F();
  Target.prototype.constructor = Target;
}
function inherit(Target, Origin) {
  Target.prototype = Object.create(Origin.prototype);
  Target.prototype.constructor = Target;
}

class

class Person {
  constructor (name, age) {
    this.name = name;
    this.age = age;
  }
  getName () {
    console.log(this.name);
  }
}
let person = new Person('aaa', 18);

等同于

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.getName = function (name) {
  console.log(this.name);
}
let person = new Person('aaa', 18);

class 继承

// Person 类
class Person {
  constructor (name, age) {
    this.name = name;
    this.age = age;
  }
  setName (name) {
    this.name = name;
  }
}

// Student 类继承自 Person 类
class Student extends Person {
  constructor (name, age, grade) {
    super(name, age); // 调用父类的构造方法
    this.grade = grade;
  }
  setGrade (grade) {
    this.grade = grade;
  }
}

let st1 = new Student('aaa', 18, 80);
console.log(st1); // Student { name: 'aaa', age: 18, grade: 80 }
st1.setName('bbb');
st1.setGrade(90);
console.log(st1); // Student { name: 'bbb', age: 18, grade: 90 }

你可能感兴趣的:(继承模式)