声明构造函数

属性声明及赋值

静态属性声明及赋值

原型方法及静态方法赋值

将属性和静态属性声明及赋值部分整理成函数

再来一个批量操作属性

将原型方法和静态方法也统一使用一个函数处理

增加一个错误机制

完整代码
"use strict";
/**
* 当你使用构造函数(Parent)的 call 的时候
* 判断你传的 实例对象 的原型链上是否存在此构造函数
* 如果不存在则直接报错
*/
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);
/**
* 将 prototype 设置为不可重写性质
* 防止直接重写 prototype
*
* Parent.prototype = {...}
*/
Object.defineProperty(Constructor, "prototype", { writable: false });
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 Parent = /*#__PURE__*/ (function () {
function Parent() {
_classCallCheck(this, Parent);
_defineProperty(this, "valueA", void 0);
_defineProperty(this, "valueB", "B");
}
_createClass(
Parent,
[
{
key: "func",
value: function func() { }
}
],
[
{
key: "staticFunc",
value: function staticFunc() { }
}
]
);
return Parent;
})();
_defineProperty(Parent, "staticValueA", void 0);
_defineProperty(Parent, "staticValueB", "B");