JavaScript 语法基础 —— 继承

原理

继承的本质我们是希望能实现以下功能:

  • 父类有的子类都有,子类也能重载,但不至于影响到父类的属性和方法
  • 除了继承之外,子类也能添加自己的方法和属性

ES6 开始支持 JavaScript 类,通过可以通过 extends 关键字继承类。

class Parent {
  constructor() {
    this.name = "Parent";
  }
  getName() {
    return this.name;
  }
}

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

let child = new Child();
console.log(child.getName());

我们可以通过 instanceof 来检验是否满足继承关系:

child instanceof Child && child instanceof Parent; // true

经过 babel 转译后的代码为:

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;
  };
})();

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
    );
  }

  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);
  }
}

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";
  }

  _createClass(Parent, [
    {
      key: "getName",
      value: function getName() {
        return this.name;
      }
    }
  ]);

  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);

var child = new Child();
console.log(child.getName());

原型链实现继承

图解原型链:

实现对象继承  的方法主要需要考虑三个方面:

  • 获得父类原型对象的  深拷贝,可以通过 Object.create 实现;
  • 拷贝父类原型对象  的 constructor 属性仍然为父类的构造函数,需要重置为子类的构造函数;
  • 子类保留对父类原型对象的引用。
// 创建一个新的对象
Object.create =
  Object.create ||
  function(proto) {
    var F = function() {};
    F.prototype = proto;
    return new F();
  };

// 实现继承
function extend(Child, Parent) {
  // 拷贝Parent原型对象
  Child.prototype = Object.create(Parent.prototype);
  // 保留对Parent原型对象的引用
  Child.__super__ = Parent.prototype;
  // 将Child原型对象构造函数重置
  Child.prototype.constructor = Child;
}

例子:

// 父类
function Parent() {
  this.name = "Parent";
}
Parent.prototype.getName = function() {
  return this.name;
};

// 子类
function Child() {
  this.name = "Child";
}

// 继承
extend(Child, Parent);

let child = new Child();
console.log(child.getName());