Home > database >  Overwrite empty string in Javascript object
Overwrite empty string in Javascript object

Time:05-02

I need that child class StringBuilder would pass the string to the parent class and call the minus method. The following code does not work unless I won't hardcode the string in the constructor. With numbers this works just fine. Why doesn't it overwrite the string? Or maybe I'm doing everything completely wrong?

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)

CodePudding user response:

Your Builder constructor does not take any parameters. Declare a parameter and assign that parameter to this.str. You can use default parameters to ensure it will be initialized to whatever you want even when the constructor is called without 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)

  • Related