Babel编译:类

编译前

class Fruit{
     static nutrition = "vitamin"
    static plant(){
     console.log('种果树'); 
    }
    name;
    constructor(name){
      this.name = name;
    }
    hello(){
      console.log(this.name);
    }
}

编译后

"use strict";

// 是否是实例
function _instanceof(left, right) {
    // 支持Symbol时,right可以是函数/对象:Symbol.hasInstance指向一个内部方法。
    if (
        right != null &&
        typeof Symbol !== "undefined" &&
        right[Symbol.hasInstance]
    ) {
        return !!right[Symbol.hasInstance](left);
    }
    // 不支持Symbol时,right必须是函数
    else {
        return left instanceof right;
    }
}

// 必须通过new运算符,调用构造函数
function _classCallCheck(instance, Constructor) {
    if (!_instanceof(instance, 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;
}

// 添加一个属性
function _defineProperty(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}

// 使用立即执行函数,创建类
var Fruit =
    /*#__PURE__*/
    (function () {
        // 类的静态方法
        _createClass(Fruit, null, [
            {
                key: "plant",
                value: function plant() {
                    console.log("种果树");
                }
            }
        ]);

        // 类对应的构造函数
        function Fruit(name) {
            // 构造函数调用检查
            _classCallCheck(this, Fruit);

            // 类的实例属性
            _defineProperty(this, "name", void 0);

            this.name = name;
        }

        // 类的实例方法
        _createClass(Fruit, [
            {
                key: "hello",
                value: function hello() {
                    console.log(this.name);
                }
            }
        ]);

        return Fruit;
    })();

// 类的静态属性
_defineProperty(Fruit, "nutrition", "vitamin");

猜你喜欢

转载自www.cnblogs.com/sea-breeze/p/11610012.html