1. ES6 Class 必须通过 new 关键字调用
  2. ES6 Class 中原型方法不能被枚举;
  3. ES6 Class中的所有代码都是处于严格模式(’use strict’)
  4. ES6 所声明的类,原型上的方法不能通过 new 调用

ES6 Class写法:

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

ES5 写法:(bable降级)

'use strict';

function _classCallCheck(instance, constructor){
    if(!(instance instanceof constructor)){
        throw new TypeError("Cannot call a class as a 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);
    }
}

function _createClass(constructor, protoProps, staticProps){
    if(protoProps){ // 原型方法
        _defineProperties(constructor.prototype, protoProps);
    }
    if(staticProps){
        _defineProperties(constructor, staticProps);
    }
    return constructor;
}

var Example = function () {
    // 构造函数
    function Example (name){
        _classCallCheck(this, Example);
        this.name = name;
    }

    _createClass(Example, [{
        key: 'init',
        value: function init(){
            var _this = this;
            function fun() {
                 console.log(_this.name) 
            }
            fun();
        }
    }],[]);

    return Example;
}();


var e = new Example('Hello');
e.init();

其他内容