这本是一篇应该记录于 EverNote 的技术杂记,然因博客太久未更新了,暂且就拿它顶一下吧。如写的不好,还请轻喷。

JavaScript,我从年初开始学 JavaScript 的时候,它依靠原型链来实现继承的事情我一直都知道,而且因为工作中一直主要在用 es6,以至于对依据原型链实现继承的这回事一直都是处于一个非常模糊的状态。结果呢,就在前几天的一次技术交流上吃了大亏,被问的哑口无言…… 因此特撰此文以明志。

使用辅助函数完成子类和父类之间原型链的连接

function inherits (Parent, Child) {
let Temp = function () {}
temp.prototype = parent.prototype
child.prototype = new Temp()
child.prototype.constructor = child
}

第一种方法即就是通过使用中间量来隔开 parent 和 child。

具体步骤如下

  1. 创建中间量——一个空函数 ( 也可以理解为一个空类 )
  2. 将空函数 Temp 的原型指向父类
  3. 创建一个 Temp 的对象 ( 暂且叫它 temp ),此时 temp 则拥有了指向Parent 的原型 __proto__ 。此时再赋给 child.prototype,这样 child 就间接有了指向 Parent 的原型。
  4. 因为 child 的原型经过了我们的特殊处理,因此需要我们修复一下它原型上的构造函数,如果不修复,也不会发生很严重的问题。

使用范例

function Student(props) {
this.name = props.name || 'Unnamed'
}
function PrimaryStudent(props) {
Student.call(this, props)
this.grade = props.grade || 1
}
// 实现原型继承链:
inherits(PrimaryStudent, Student)

使用官方的 Object.create()

function inherits (Parent, Child) {
child.prototype = Object.create(Parent.prototype)
child.prototype.constructor = Child
}

这里包装成方法,主要是图方便,实际应用中最好不要这么写… 上一种方式封装方法主要是为了屏蔽 Temp 辅助方法。

donation