【发布时间】:2020-01-26 04:41:54
【问题描述】:
我有一个基本的 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,因为它是一个被添加到字符串中的数字。
【问题讨论】:
-
根据您的逻辑,“005”+ 5 变成“0055”,因为数字是 55,小于 100,在前面加上“0”,然后变成“00055”。字符串转换是你的问题。
-
不,没有办法避免这种情况,只能有一个数字
.id属性和一个 单独paddedId字符串获取器。
标签: javascript getter-setter assignment-operator es6-class