鍍金池/ 問答/HTML/ ES6中class extends實現(xiàn)繼承,是基于ES5的那種繼承?組合繼承嗎?

ES6中class extends實現(xiàn)繼承,是基于ES5的那種繼承?組合繼承嗎?

ES6的classextends是ES5的語法糖,那是不是說ES6其實使用的也是ES5的繼承方式,比如組合繼承?寄生組合繼承?還是ES6使用了不同的方式實現(xiàn)繼承?

回答
編輯回答
撿肥皂

通過babel轉(zhuǎn)義的代碼看出來應(yīng)該是原型繼承


class A {
  constructor(a) {
    this.a = a;
  }
  getA() {
    console.log(a)
  }
}

class B extends A {
  constructor(b) {
    super()
    this.b = b;
  }
}

轉(zhuǎn)義后

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

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 A = function () {
  function A(a) {
    _classCallCheck(this, A);

    this.a = a;
  }

  _createClass(A, [{
    key: "getA",
    value: function getA() {
      console.log(a);
    }
  }]);

  return A;
}();

var B = function (_A) {
  _inherits(B, _A);

  function B(b) {
    _classCallCheck(this, B);

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

    _this.b = b;
    return _this;
  }

  return B;
}(A);
2017年9月16日 06:54