ES6类语法转ES5构造函数

69 阅读1分钟

ES6

class Example {
  constructor(name) {
    this.name = name;
  }
  init() {
    const fun = () => {
      console.log(this.name);
    };
    fun();
  }
}
const e = new Example('Hello');
e.init();

ES5

四个注意的点

  1. ES6的class必须通过new来调用
  2. ES6的class中的所有代码均处于严格模式下
  3. ES6中,原型上的方法不可枚举
  4. 原型上的方法不可通过new调用
function Example(name){
    'use strict'
    if(!new.target){
        throw new Error("Class constructor cannot be invoked without new");
    }
    this.name = name
}

Object.defineProrperty(Example.prototype, "init", {
    enumerable: false;
    value: function(){
        'use strict'
        if(new.target){
            throw new Error("init is not a contructor");
        }
        var fun = function(){
            console.log(this.name);
        }
        fun.call(this);
    }
})

手撕代码系列