由于这类语言严格区分类和实例,继承实际上是类型的扩展。但是,JavaScript由于采用原型继承,我们无法直接扩展一个Class,因为根本不存在Class这种类型。

    但是办法还是有的。我们先回顾构造函数:

    以及Student的原型链:

    现在,我们要基于Student扩展出PrimaryStudent,可以先定义出PrimaryStudent

    1. function PrimaryStudent(props) {
    2. // 调用Student构造函数,绑定this变量:
    3. Student.call(this, props);
    4. this.grade = props.grade || 1;
    5. }

    但是,调用了Student构造函数不等于继承了StudentPrimaryStudent创建的对象的原型是:

    1. new PrimaryStudent() -> PrimaryStudent.prototype -> Student.prototype -> Object.prototype -> null

    这样,原型链对了,继承关系就对了。新的基于PrimaryStudent创建的对象不但能调用PrimaryStudent.prototype定义的方法,也可以调用Student.prototype定义的方法。

    如果你想用最简单粗暴的方法这么干:

    是不行的!如果这样的话,PrimaryStudentStudent共享一个原型对象,那还要定义PrimaryStudent干啥?

    我们必须借助一个中间对象来实现正确的原型链,这个中间对象的原型要指向Student.prototype。为了实现这一点,参考道爷(就是发明JSON的那个道格拉斯)的代码,中间对象可以用一个空函数F来实现:

    1. // PrimaryStudent构造函数:
    2. function PrimaryStudent(props) {
    3. Student.call(this, props);
    4. this.grade = props.grade || 1;
    5. }
    6. // 空函数F:
    7. function F() {
    8. // 把F的原型指向Student.prototype:
    9. F.prototype = Student.prototype;
    10. // 把PrimaryStudent的原型指向一个新的F对象,F对象的原型正好指向Student.prototype:
    11. // 把PrimaryStudent原型的构造函数修复为PrimaryStudent:
    12. PrimaryStudent.prototype.constructor = PrimaryStudent;
    13. // 继续在PrimaryStudent原型(就是new F()对象)上定义方法:
    14. PrimaryStudent.prototype.getGrade = function () {
    15. return this.grade;
    16. };
    17. // 创建xiaoming:
    18. var xiaoming = new PrimaryStudent({
    19. name: '小明',
    20. grade: 2
    21. });
    22. xiaoming.name; // '小明'
    23. xiaoming.grade; // 2
    24. // 验证原型:
    25. xiaoming.__proto__ === PrimaryStudent.prototype; // true
    26. xiaoming.__proto__.__proto__ === Student.prototype; // true
    27. // 验证继承关系:

    用一张图来表示新的原型链:

    js-proto-extend

    如果把继承这个动作用一个inherits()函数封装起来,还可以隐藏F的定义,并简化代码:

    这个inherits()函数可以复用:

    1. function Student(props) {
    2. this.name = props.name || 'Unnamed';
    3. }
    4. Student.prototype.hello = function () {
    5. alert('Hello, ' + this.name + '!');
    6. }
    7. function PrimaryStudent(props) {
    8. Student.call(this, props);
    9. this.grade = props.grade || 1;
    10. }
    11. // 实现原型继承链:
    12. inherits(PrimaryStudent, Student);
    13. // 绑定其他方法到PrimaryStudent原型:
    14. PrimaryStudent.prototype.getGrade = function () {
    15. return this.grade;
    16. };

    JavaScript的原型继承实现方式就是:

    1. 定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this

    2. 继续在新的构造函数的原型上定义新方法。

    读后有收获可以支付宝请作者喝咖啡,读后有疑问请加微信群讨论: