ES6 class 继承

158 阅读1分钟

随便写一个ES6继承的demo

class Father {
    constructor(name) {
        this.name = name
    }
    getName(){
        return this.name
    }
}

class Son extends Father {
    constructor(name, age) {
        super(name)
        this.age = age
    }
    setName(name){
    	this.name = name
    }
}
const son = new Son('jay', 18)
console.log(son.getName()) // jay
son.setName('bob')
console.log(son.getName()) // bob

ES6的继承,需要子类调用super方法来初始化this, 可以通过babel在线编译去看一下背后的逻辑.

以下就是babel编译之后的结果

"use strict";

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }

var Father = /*#__PURE__*/function () {
  function Father(name) {
    this.name = name;
  }

  var _proto = Father.prototype;

  _proto.getName = function getName() {
    return this.name;
  };

  return Father;
}();

var Son = /*#__PURE__*/function (_Father) {
  _inheritsLoose(Son, _Father);

  function Son(name, age) {
    var _this;

    _this = _Father.call(this, name) || this;
    _this.age = age;
    return _this;
  }

  var _proto2 = Son.prototype;

  _proto2.setName = function setName(name) {
    this.name = name;
  };

  return Son;
}(Father);

var son = new Son('jay', 18);
console.log(son.getName()); // jay

son.setName('bob');
console.log(son.getName()); // bob

从结果中我们可以看到 extends 背后的逻辑

  1. 先创建 _this, 通过父类 Father 修饰之后再添加子类的属性
  2. 将子类的原型对象指向父类的原型对象,并且把子类的__proto__指向父类
  3. 在子类的原型对象上面添加自己的方法和属性