为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法让算术运算符在 Javascript ES6 中使用 getter 和 setter?

有没有办法让算术运算符在 Javascript ES6 中使用 getter 和 setter?

慕莱坞森 2021-10-29 15:07:25
我有一个基本的 ID 系统,其中一个数字被转换成一个字符串并用零填充至少为 3 位数字。只要我只使用常规作业,它就可以正常工作。有没有办法让算术运算符也与 setter 一起使用?class Test {  constructor() {    this.id = 0;  }  /**   * @param {Number} num   */  set id(num) {    if (num < 10) {      this._id = '00' + num;    } else if (num < 100) {      this._id = '0' + num;    } else {      this._id = '' + num;    }  }  get id() {    return this._id;  }  incrementID(increment=1) {    const id = parseInt(this.id);    this.id = id + increment;  }}const test = new Test();test.id = 5;console.log(`ID is: ${test.id}`); // ID is: 005test.id += 5;console.log(`ID is: ${test.id}`); // ID is: 00055 (How?!?)我知道我可以拥有一种incrementID像我写的那样的方法,但感觉这违背了 ES6 的 setter 和 getter 的理念。作为旁注,加法赋值到底发生了什么?我原以为结果会0055很奇怪,因为它是一个数字被添加到字符串中。
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信