您可以嘗試使用靜態吸氣實現代碼的最初打算層次:
class Module {
static get name() { return "Default Module"; }
static get version() { return {major:10000, minor: 10000}; }
static parse() {
console.log(this.name);
}
}
class ExtendedModule extends Module {
static get name() { return "Extended"; }
static get version() { return {major:1, minor: 0}; }
}
ExtendedModule.parse();
使用BabelJS這成爲
"use strict";
var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Module = function() {
function Module() {
_classCallCheck(this, Module);
}
_createClass(Module, null, [{
key: "parse",
value: function parse() {
console.log(this.name);
}
}, {
key: "name",
get: function get() {
return "Default Module";
}
}, {
key: "version",
get: function get() {
return { major: 10000, minor: 10000 };
}
}]);
return Module;
}();
var ExtendedModule = function (_Module) {
_inherits(ExtendedModule, _Module);
function ExtendedModule() {
_classCallCheck(this, ExtendedModule);
return _possibleConstructorReturn(this, (ExtendedModule.__proto__ || Object.getPrototypeOf(ExtendedModule)).apply(this, arguments));
}
_createClass(ExtendedModule, null, [{
key: "name",
get: function get() {
return "Extended";
}
}, {
key: "version",
get: function get() {
return { major: 1, minor: 0 };
}
}]);
return ExtendedModule;
}(Module);
ExtendedModule.parse();
運行代碼,它是在顯示
Extended
JS控制檯。
這不是ES6。 ES6沒有類屬性初始值設定項。 –
另外,'Module.name'是'「Module」(它仍然是一個命名的構造函數)。你不能在其上放置另一個'.name'。 – Bergi
@Bergi雖然它可能會導致框架或類似的問題,例如爲了創建一些調試輸出而試圖讀取名稱,您絕對可以在其上放置另一個'.name'。對Javascript來說這很棒:你可以很容易地破解事情,但你仍然可以做到。 ;) – cepharum