ES6中的类经过babel编译后会降级生成ES5的代码,用来兼容新老版本的浏览器。
通过看编译后的ES5的代码,自己来模拟实现一下ES6中的类。
主要模拟三点功能:
1.ES5中模拟类的构造函数不能直接执行,只能通过new来执行。
2.静态属性的模拟。
3.原型链上属性的模拟。
function _inherit (sub, sup) {
Object.setPrototypeOf(sub.prototype, sup.prototype);
}
function _classCallCheck (_this, _constructor) {
if (! (_this instanceof _constructor) ) {
throw "TypeError: Class constructor Plane cannot be invoked without 'new'";
}
};
// 处理公有属性和静态属性
//
function _defineProperties (target, props) {
// Object.defineProperty
props.forEach(function (ele) {
// ele.key ele.value
Object.defineProperty(target, ele.key, {
value: ele.value,
writable: true,
configurable: true
});
})
}
function _createClass (_constructor, _prototypeProperties, _staticProperties) {
// 给原型上赋值
if (_prototypeProperties) {
_defineProperties(_constructor.prototype, _prototypeProperties);
}
if (_staticProperties) {
_defineProperties(_constructor, _staticProperties);
}
}
var Plane = (function () {
function Plane (name) {
// 判断是否以new的方式来执行
_classCallCheck(this, Plane);
this.name = name || '普通飞机';
this.blood = 100;
}
_createClass(Plane, [
{
key: 'fly',
value: function () {
console.log('fly');
}
}
], [
{
key: 'alive',
value: function () {
return true;
}
}
]);
return Plane;
})();
var AttackPlane = (function (Plane) {
_inherit(AttackPlane, Plane);
function AttackPlane (name) {
_classCallCheck(this, Plane);
var _this = this;
var that = Plane.call(_this, name);
if (typeof that == 'object') {
_this = that;
}
_this.logo = 'duyi';
return _this;
};
_createClass(AttackPlane, [
{
key: 'dan',
value: function () {
console.log('biubiubiu');
}
}
], [
{
key: 'alive',
value: function () {
return true;
}
}
]);
return AttackPlane;
})(Plane);