class继承的原理及代码实现

122 阅读1分钟

class继承写法

class F {
  constructor(name){
    this.name = name
  }
}
class S extends F {
    constructor(name, age) {
        super(name)
    }
}

function的实现方式

const _extends = (() => {
  let extendtatics = (() => {
    function getStaticsByForIn(s, p) {
      for(let key in p) {
        if(p.hasOwnProperty(key)) {
          s[key] = p[key]
        }
      }
    }
    function getStaticsByObjectKeys(s, p) {
      Object.keys(p).forEach(key => {
        s[key] = p[key]
      })
    }
    function getStaticsByProto() {
      s.__proto__ = p
    }
    return Object.setPrototypeOf || getStaticsByProto || getStaticsByObjectKeys || getStaticsByForIn
  })()
  return (Son, Parent) => {
    if(typeof Parent !== 'function' && Parent !== null) {
      new TypeError(`Class extends value ${String(Parent)} is not a constructor`)
    }
    extendtatics(Son, Parent)
    function __() {
      this.constructor = Son
    }
    Son.prototype = Parent === null ? Object.create(Parent) : (__.prototype = Parent.prototype, new __())
  }
})()

const F = (function () {
    function F(name) {
        this.name = name;
    }
    return F;
}())
const S = (function(_super) {
    _extends(S, _super)
    function S(name, age) {
        let _this = _super.call(this, name) || this
        _this.age = age
        return _this
    }
    return S
})(F)