覆盖 Javascript 对象中的空字符串
Overwrite empty string in Javascript object
我需要子 class StringBuilder 将字符串传递给父 class 并调用 minus 方法。除非我不在构造函数中对字符串进行硬编码,否则以下代码不起作用。对于数字,这很好用。为什么它不覆盖字符串?或者也许我做的一切都完全错误?
class Builder {
constructor() {
this.int = 0
this.str = ''
}
minus(...n) {
this.int = n.reduce((sum, current) => sum - current, this.int)
this.str = this.str.slice(0, -n)
return this
}
}
class IntBuilder extends Builder {
constructor(int) {
super(int)
}
}
class StringBuilder extends Builder {
constructor(str) {
super(str)
}
}
let number = new IntBuilder()
number.minus(100, 99)
console.log(number)
let string = new StringBuilder('Hello')
string.minus(2)
console.log(string)
您的 Builder 构造函数不带任何参数。声明一个参数并将该参数分配给 this.str
。你可以使用 default parameters 来确保它被初始化为你想要的任何东西,即使在没有参数的情况下调用构造函数。
class Builder {
constructor(str = "") {
this.int = 0
this.str = str
}
minus(...n) {
this.int = n.reduce((sum, current) => sum - current, this.int)
this.str = this.str.slice(0, -n);
return this;
}
}
class IntBuilder extends Builder {
constructor(int) {
super(int)
}
}
class StringBuilder extends Builder {
constructor(str) {
super(str)
}
}
let number = new IntBuilder()
number.minus(100, 99)
console.log(number)
let string = new StringBuilder('Hello')
string.minus(2)
console.log(string)
我需要子 class StringBuilder 将字符串传递给父 class 并调用 minus 方法。除非我不在构造函数中对字符串进行硬编码,否则以下代码不起作用。对于数字,这很好用。为什么它不覆盖字符串?或者也许我做的一切都完全错误?
class Builder {
constructor() {
this.int = 0
this.str = ''
}
minus(...n) {
this.int = n.reduce((sum, current) => sum - current, this.int)
this.str = this.str.slice(0, -n)
return this
}
}
class IntBuilder extends Builder {
constructor(int) {
super(int)
}
}
class StringBuilder extends Builder {
constructor(str) {
super(str)
}
}
let number = new IntBuilder()
number.minus(100, 99)
console.log(number)
let string = new StringBuilder('Hello')
string.minus(2)
console.log(string)
您的 Builder 构造函数不带任何参数。声明一个参数并将该参数分配给 this.str
。你可以使用 default parameters 来确保它被初始化为你想要的任何东西,即使在没有参数的情况下调用构造函数。
class Builder {
constructor(str = "") {
this.int = 0
this.str = str
}
minus(...n) {
this.int = n.reduce((sum, current) => sum - current, this.int)
this.str = this.str.slice(0, -n);
return this;
}
}
class IntBuilder extends Builder {
constructor(int) {
super(int)
}
}
class StringBuilder extends Builder {
constructor(str) {
super(str)
}
}
let number = new IntBuilder()
number.minus(100, 99)
console.log(number)
let string = new StringBuilder('Hello')
string.minus(2)
console.log(string)