简单易懂的继承模式详解

163 阅读1分钟

继承模式

原型链继承

1.套路

  1. 定义父类型构造函数
  2. 给父类型的原型添加方法
  3. 定义子类型的构造函数
  4. 创建父类型的对象赋值给子类型的原型
  5. 将子类型原型的构造属性设置为子类型
  6. 给子类型原型添加方法
  7. 创建子类型的对象:可以调用父类型的方法

2.关键

  • 子类型的原型为父类型的一个实例对象,构造函数的实例对象隐式原型指向其构造函数的显式原型对象,再说明白点就是,子类型的原型的隐式原型可以指向父类型的显式原型,那么其中的方法就会被子类型看见

    Son.prototype = new Father() //赋值,注意不是声明  改变Son.prototype的原有地址值,改变其指向为Father.prototype  new Father()是其实例对象
    

image.png 【注】当使用继承时,为保证子类型的原型constructor属性指向子类型!Son.prototype.constructor = Son

借用构造函数继承(假继承)

  1. 套路

    1. 定义父类型构造函数
    2. 定义子类型构造函数
    3. 在子类型构造函数中调用父类型构造
  2. 关键

    1. 在子类型构造函数中通用call()调用父类型构造函数

组合继承

  1. 利用原型链继承实现对父类型对象的方法继承
  2. 利用call()借用父类型构造函数初始化相同属性
function Person(name,age){
    this.name = name
    this.age = age
}
person.prototype.setName = function (name) {
    this.name = name
}
​
function Student(name,age,price){
    Person.call(this,name,price) //获取属性 tihs.Person(name, age)
    this.price = price
}
Student.protoytype = new Person ()//获取父类方法
Student.protoytype.constructor = Student//修正constructor属性,使其指向Student
Student.prototype.setPrice = function(price){
    this.price = price
}
var s = new Student("a",10,15000)
s.setName("b")
s.setPrice("20000")
console.log(s.name,s.age,s.price)
​