【JS】将class转为构造函数需要注意的细节

前言

将 class 转为构造函数看似很简单,但作为封装者,有很多注意事项

class Person {
  constructor(name) {
    this.name = name;
  }
  fn() { console.log(this.name); }
}

实现

初步转化如下:

function Person() {
  this.name = name
}
Person.prototype.fn = function () { console.log(this.name); }

ES6使用类处于严格模式

'use strict'

function Person() {
  this.name = name
}
Person.prototype.fn = function () { console.log(this.name); }

类只能通过 new 调用,但是构造函数没有该限制

在这里插入图片描述

通过 this 指向判断是否使用 new

'use strict'

function Person() {
  // 验证 this 指向
  if (!(this instanceof Person)) {
    throw new Error('请使用 new 关键字调用')
  }
  this.name = name
}
Person.prototype.fn = function () { console.log(this.name); }

类的 方法成员不可枚举

在这里插入图片描述

但构造函数没有限制

在这里插入图片描述

通过 Object.defineProperty 限制不可枚举

'use strict'

function Person() {
  // 验证 this 指向
  if (!(this instanceof Person)) {
    throw new Error('请使用 new 关键字调用')
  }
  this.name = name
}

Object.defineProperty(Person.prototype, 'fn', {
  value: function () { console.log(this.name); },
  enumerable: false, // 方法成员不可枚举
})

const p = new Person('田本初')
for (const key in p) {
  console.log(key);
}

JS中所有的函数都可以使用new调用,但是类的方法成员不行

在这里插入图片描述

同样根据this指向判断

'use strict'
function Person() {
  // 验证 this 指向
  if (!(this instanceof Person)) {
    throw new Error('请使用 new 关键字调用')
  }
  this.name = name
}
Object.defineProperty(Person.prototype, 'fn', {
  value: function () { 
    if (!(this instanceof Person)) {
    throw new Error('不能使用 new 关键字调用')
  }console.log(this.name); },
  enumerable: false,
})

总结

将class转为构造函数需要注意如下几点:

  1. 类在严格模式
  2. 只能通过 new 关键字调用
  3. 方法成员不可枚举
  4. 方法成员无法通过 new 调用
  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田本初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值