我有一个基本的 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: 005
test.id += 5;
console.log(`ID is: ${test.id}`); // ID is: 00055 (How?!?)
我知道我可以拥有一种incrementID像我写的那样的方法,但感觉这违背了 ES6 的 setter 和 getter 的理念。
作为旁注,加法赋值到底发生了什么?我原以为结果会0055很奇怪,因为它是一个数字被添加到字符串中。
相关分类