从下列代码可以看出 Person 和Student中存在大量耦合代码

function Person(name, sex, age){
      this.name = name;
      this.sex = sex;
      this.age = age;
}

function Student(name, sex, age, grade){
      this.name = name;
      this.sex = sex;
      this.age = age;
      this.grade = grade;
}

call apply模式

// call模式
function Student(name, sex, age, grade){
      Person.call(this,name, sex, age)
      this.grade = grade;
}
//apply模式
function Student(name, sex, age, grade){
      Person.apply(this.[name, sex, age])
}

原型链

Person.prototype.name = '张三'
function Person(){

}
function Student(){
      this.sex = '男'
}

const person = new Person()
Student.prototype = person
const student = new Student()
console.log(student.name) // ==> '张三'
 // student.__proto__ ==> Student.prototype ==> Student.prototype.__proto__ ==>Person ... Object.prototype

787416-20160322110905589-2039017350

共享原型

​ 缺点:会造成两边原型一样

Person.prototype = Student.prototype
const person = new Person()
const student = new Student()
/*--------------------------------------*/
//抽象
function extend(Target, Origin){
      Target.prototype = Origin.prototype
}
extend(Student, Person)
const person = new Person()
const student = new Student()

圣杯模式

function extend(Target, Origin){
      function F(){}
      F.prototype = Origin
      Target.prototype = new F()
      Target.prototype.constuctor = Target
      //uber ==> super
      Target.prototype.uber = Origin.prototype
}
extend(Student, Person)
const person = new Person()
const student = new Student()
//person.__proto__ ==> new F().__proto__ ==> Origin.prototype

ES6 继承

class Student extends Person{

}