浅析Javascript类的继承

继承

构造函数继承

function Parent() {
    this.name='parent';
}

Parent.prototype.run=function () {
    console.log('We can run');
}

function Child() {
    Parent.call(this);
}

let c=new Child();
c.name; // 'parent'
c.run(); // undefined
  • 缺点
  1. 无法继承父类原型上的方法

原型链实现继承

function Parent() {
    this.name='parent';
    this.colors=["red","yellow"];
}

Parent.prototype.run=function () {
    console.log('We can run');
}

function Child() {
    
}

Child.prototype=new Parent();
Child.prototype.constructor=Child;   

var c1=new Child();
var c2=new Child();

c1.colors; // ['red','yellow']
c2.colors; // ['red','yellow']

c1.colors.push('green');

c1.colors; // ['red','yellow','green']
c2.colors; // ['red','yellow','green']
  • 缺点
  1. 子类共用一个父类的实例,造成数据污染
  2. 创建子类实例时,无法向父类构造函数传参

组合式继承

function Parent() {
    this.name='parent';
    this.colors=["red","yellow"];
    console.log("I've executed");
}

Parent.prototype.run=function () {
    console.log('We can run');
}

function Child() {
    Parent.call(this);
}

Child.prototype=new Parent();
Child.prototype.constructor=Child;

var c1=new Child(); // "I've executed" "I've executed"
var c2=new Child(); // "I've executed" "I've executed"

c1.colors; // ['red,yellow']
c2.colors; // ['red,yellow']

c1.colors.push('green');

c1.colors; // ['red,yellow','green']
c2.colors; // ['red,yellow']
  • 缺点
  1. 每新建一个子类都会调用两次父类构造器

寄生组合式继承


function Parent() {
    this.name='parent';
    this.colors=["red","yellow"];
}

Parent.prototype.run=function () {
    console.log('We can run');
}


function Child() {
    Parent.call(this);
}
function Super() {/* noop */}
Super.prototype=Parent.prototype;
Child.prototype=new Super();
Child.prototype.constructor=Child;

  • 特点
  1. 完美实现继承
  2. 利用寄生函数实现父类构造函数只执行一次,将原型上的方法挂载到寄生函数上,最后将寄生函数的实例作为子类的原型对象

ES6 继承


class Parent {
    constructor() {
        this.name='parent';
        this.colors=["red","yellow"];
    }
    run() {
        console.log('We can run');
    }
}

class Child extends Parent{
    constructor() {
        super();
        this.name='child';
    }
}

  • 特点
  1. 简单明了
  2. 只是一种语法糖而已
  • 下面是babel将ES6转成ES5继承的实现

Babel 编译后的ES5代码

"use strict";

// 创建类
var _createClass = function() {
    function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value"in descriptor)
                descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor);
        }
    }
    return function(Constructor, protoProps, staticProps) {
        // 定义原型对象的属性、方法
        if (protoProps)
            defineProperties(Constructor.prototype, protoProps);
        // 定义类的静态属性、方法
        if (staticProps)
            defineProperties(Constructor, staticProps);
        return Constructor;
    }
    ;
}();
// 确保子类初始化时调用super
function _possibleConstructorReturn(self, call) {
    if (!self) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
// 继承
function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
    }
    // 利用 Object.crete 创建了一个父类原型对象的新实例,并且修正了构造器指向
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    // 将子类原型链链到父类上
    if (superClass)
        Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
// 安全检测,确保用 'new' 操作的构造函数
function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}

var Parent = function() {
    function Parent() {
        _classCallCheck(this, Parent);

        this.name = 'parent';
        this.colors = ["red", "yellow"];
    }

    _createClass(Parent, [{
        key: "run",
        value: function run() {
            console.log('We can run');
        }
    }]);

    return Parent;
}();

var Child = function(_Parent) {
    _inherits(Child, _Parent);

    function Child() {
        _classCallCheck(this, Child);

        var _this = _possibleConstructorReturn(this, (Child.__proto__ || Object.getPrototypeOf(Child)).call(this));

        _this.name = 'child';
        return _this;
    }

    return Child;
}(Parent);


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文先对es6发布之前javascript各种继承实现方式进行深入的分析比较,然后再介绍es6中对类继承的支持以及...
    lazydu阅读 16,755评论 7 44
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 9,532评论 3 11
  • JavaScript面向对象程序设计 本文会碰到的知识点:原型、原型链、函数对象、普通对象、继承 读完本文,可以学...
    moyi_gg阅读 4,090评论 0 2
  • 第3章 基本概念 3.1 语法 3.2 关键字和保留字 3.3 变量 3.4 数据类型 5种简单数据类型:Unde...
    RickCole阅读 10,620评论 0 21
  • 通过列表下标获取下标所对应列表中的值 [0---len] 值 = 列表[下标] 通过值获取在列表中对应的下标 ...
    风雨的问候阅读 3,030评论 0 0