ES6 类class转化为 构造函数
例子
class Example {
constructor(name) {
this.name = name
}
func() {
console.log(this.name)
}
}
常规写法
function Example(name) {
this.name = name
}
Example.prototype.func = function () {
console.log(this.name)
}
标准写法
注意事项
- class 转化为构造函数需要在严格模式下 ‘use strict’
- 构造函数只能通过 new 调用
- 构造函数中的方法不可被枚举
- 构造函数中的方法不可被 new 调用
需要使用的方法
Object.defineProperty(obj, prop, descriptor)查看具体定义:会直接在一个对象上定义一个新属性,或修改其现有属性,并返回此对象。
- obj:要定义属性的对象
- prop:一个字符串或 Symbol,指定了要定义或修改的属性键
- descriptor:要定义或修改的属性的描述符
转化结果
// 1.需要使用严格模式
'use strict'
function Example(name) {
// 2.判断是否是使用 new 来构造的,如果是使用 new 来调用的,则新创建出来的对象是 Example 的实例,
// 否则在严格模式下,this 的指向是 undefined
if (!(this instanceof Example)) {
throw new TypeError('Class constructor Example cannot be invoked without new')
}
this.name = name
}
// 如果需要设置不可枚举则需要使用 Object.defineprototy 方法
Object.defineprototy(Example.prototype, 'func', {
value: function() {
// 4.设置 func 函数不可被实例化, 即不可被 new 调用,判断方法同上面判断相同
if (!(this instanceof Expamle)) {
throw new TypeError('obj.func is not a constructor')
}
console.log(this.name)
},
// 3.设置为不可枚举
enumerable: false
})