webpack+babel打包出的class是怎麼個實現

某天突然想看看ES6的class是怎麼個實現法,就隨便寫了個簡單的例子試了試,先看例子

// add.js
export default class Add {
  add(a, b) {
    return a + b;
  }

  minus(a, b) {
    return a - b;
  }

  static hah() {
    console.log("hah");
  }
  
  static test = 5;

  val = 2;
}

Add.nihao = function() {
  console.log("nihao");
};


//main.js

import Add from "./add";
console.log(new Add().add(1, 3));

我們用webpack打包編譯(babel 7.0.0),@babel/plugin-proposal-class-properties不知道有沒有關係

得到的結果如下,Add上面定義的成員變量、靜態變量都通過_defineProperty來定義,成員函數定義到prototype上面,靜態函數定義到構造函數上,總的來說比較清晰簡潔

"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;
}

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 Add =
  function () {
    function Add() {
      _classCallCheck(this, Add);

      _defineProperty(this, "val", 2);
    }

    _createClass(Add, [{
      key: "add",
      value: function add(a, b) {
        return a + b;
      }
    }, {
      key: "minus",
      value: function minus(a, b) {
        return a - b;
      }
    }], [{
      key: "hah",
      value: function hah() {
        console.log("hah");
      }
    }]);

    return Add;
  }();

_defineProperty(Add, "test", 5);

Add.nihao = function () {
  console.log("nihao");
};

console.log(new Add().add(1, 3));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章