示例:
class A { // 屬性表達式 prop1 = 1; // get方法 get value() { console.log('Getting the current value!'); return this.prop1; } // set方法 set value(newValue) { console.log('Setting the current value!'); this.prop1 = newValue; } // 箭頭函數表達式 arrowFunc = (...args) => { console.log(args); } // constructor constructor(b = 2) { this.prop2 = b; } // 普通函數表達式 Func() { console.log("Func"); } // 靜態屬性 static prop3 = 3; // 靜態普通函數 static staticFunc() { console.log("staticFunc", this); } // 靜態箭頭函數 static staticArrowFunc = () => { console.log("staticArrowFunc", this); } } const a = new A(3);
使用babel編譯成es5的代碼,編譯結果會生成幾個內部函數:
// 類的調用檢查,如果調用A不使用new,則會報錯 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); } } // 定義原型上的普通函數、靜態普通函數、get和set方法
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } // 定義屬性到obj上,重新賦值使用defineProperty,第一次賦值直接添加屬性 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; }
類的編譯結果:
// A是一個立即執行函數 返回結果是個函數 函數名就是類名 var A = /*#__PURE__*/ (function () { // constructor function A() { // 轉化constructor中的默認參數 var b = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2; // 檢查類是否使用new執行 _classCallCheck(this, A); // 屬性表達式定義到類實例上 _defineProperty(this, "prop1", 1); // 箭頭函數表達式定義到類實例上 _defineProperty(this, "arrowFunc", function () { // 這個for循環是轉換...args,遍歷arguments,將每一項賦值給args對象 for ( var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++ ) { args[_key] = arguments[_key]; } console.log(args); }); this.prop2 = b; } _createClass( A, [ {// get和set方法 key: "value", get: function get() { console.log("Getting the current value!"); return this.prop1; }, set: function set(newValue) { console.log("Setting the current value!"); this.prop1 = newValue; } }, {// 普通函數表達式 key: "Func", value: function Func() { console.log("Func"); } } ], [ {// 靜態普通函數 key: "staticFunc", value: function staticFunc() { console.log("staticFunc", this); } } ] ); return A; })(); // 靜態屬性定義到類上 _defineProperty(A, "prop3", 3); // 靜態箭頭函數定義到類上 _defineProperty(A, "staticArrowFunc", function () { console.log("staticArrowFunc", A); }); var a = new A(3);
下圖可描述整個編譯結果:

需要注意的是:
- 類原型上的方法、類的靜態方法、類的get和set方法默認是不可枚舉的
- 類實例上的方法和屬性、類的靜態箭頭函數是可枚舉的
之后再出一章class繼承的相關內容
浙公網安備 33010602011771號