一次性搞定面向对象

98 阅读1分钟

面向对象自查清单

  • 类与实例:类的声明,生成实例
  • 类与继承:如何实现继承,继承的几种方式

实现继承的几种方式(继承的本质就是原型链

借助构造函数实现继承

function Parent() {
    this.name = 'Parent'
}
function Child() {
    Parent.call(this)  // 通过改变this指向,父类执行的方法属性都会挂载在子类的实例
    this.type = 'Child'
}

缺点:父类原型链的方法和属性并不会被子类所继承

借助原型链实现继承

function Parent() {
    this.name = 'Parent'
}
function Child() {
    this.type = 'Child'
}
Child.prototype = new Parent()

// new Child().__proto__ === Child.prototype

缺点:原型链的上的方法是公用的,引用类型的更改子类都会受到影响

组合方法实现继承

function Parent() {
    this.name = 'Parent'
}
function Child() {
    Parent.call(this) // 父类构造函数第一次执行
    this.type = 'Child'
}
Child.prototype = new Parent() // 父类构造函数第二次执行

缺点:实例化对象的时候父类构造函数执行了两次,两次并没有必要

组合方法优化的实现继承方式1

function Parent() {
    this.name = 'Parent'
}
function Child() {
    Parent.call(this) 
    this.type = 'Child'
}
Child.prototype = Parent.prototype // 简单的引用并不会二次执行父类的构造函数

缺点:不能直接判断是由子类还是父类直接实例化完成

组合方法优化的实现继承方式2

function Parent() {
    this.name = 'Parent'
}
function Child() {
    Parent.call(this) 
    this.type = 'Child'
}
Child.prototype = Object.create(Parent.prototype)Child.prototype.constructor = Child