将 class 声明的类 转化为普通的构造函数。
class Example {
constructor(msg) {
this.msg = msg;
}
func() {
console.log(this.msg);
}
}
1.模式
ES6的类是整个处于 严格模式 下的,所以转化后的 普通函数 也是处于严格模式下的。
"use strict";
function Example() {}
2.调用方式
class必须使用 new关键字来调用,如果不用则会报错.
因此,转换为 普通构造函数 后,如果普通调用,也要报一样的错误。
function Example(msg) {
//是否使用 `new` 关键字在调用
if (!new.target) {
//undefined 则是一般调用
throw new TypeError(
`Class constructor Example cannot be invoked without 'new'`
);
}
this.msg = msg;
}
Example.prototype.func = function () {
console.log("this.msg", this.msg);
};
3. 枚举
通过class声明 new出来的 对象,只有属性是可以枚举的,方法是不可枚举的。因此,需要通过 属性描述符 将方法设为不可枚举。
Object.defineProperty(Example.prototype, "func", {
value: function () {
console.log("this.msg", this.msg);
},
enumerable: false,//不可枚举
});
4. 方法的调用
class类里的方法不能通过 new关键字来调用,否则报错。转化后的 普通构造函数 也应如此。
Object.defineProperty(Example.prototype, "func", {
value: function () {
//不能使用 `new` 来调用
if (new.target) {
throw new TypeError(`example.prototype.func is not a constructor`);
}
console.log("this.msg", this.msg);
},
enumerable: false,
});
完整代码
//xxx.js
"use strict";
function Example(msg) {
//是否使用 `new` 关键字在调用
if (!new.target) {
//undefined 则是一般调用
throw new TypeError(
`Class constructor Example cannot be invoked without 'new'`
);
}
this.msg = msg;
}
Object.defineProperty(Example.prototype, "func", {
value: function () {
//不能使用 `new` 来调用
if (new.target) {
throw new TypeError(`example.prototype.func is not a constructor`);
}
console.log("this.msg", this.msg);
},
enumerable: false,
});
export default Example;