4

I'm trying to use getters and setters to adjust data initially set with a class constructor. The getter seems to work:

class myClass {
  constructor(sth) {
    this.data = {
      sth,
      timestamp: new Date()
    }
  }
  
  create(createData) {
    const newData = Object.assign({}, this.theData, {
    /*      this getter seems to work ^^^^^^^^^^^^ */
      createData
    })
    console.log(newData) // looks good
    // set'ter new data
    this.theData(newData)
    return this
  }
  
  get theData() {
    return this.data
  }
  
  set theData(newData) {
    console.log('setting')
    this.data = newData;
  }
}
         
const Instance = new myClass('construct data')
  .create({createData: 'some data'})

But this gets the error

zakeyumidu.js:27 Uncaught TypeError: this.theData is not a function

at myClass.create

creating a non-setter method seems to work as I can just do

setTheData(newData) {
  this.data = newData // yep, that works
}

But I get the idea that getters/setters are preferred.

Is it okay to set instance data like this within class methods like my example that works? If not, why is my setter not working?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229

2 Answers2

4

Instead of this.theData(newData) you should write this.theData = newData

class myClass {
  constructor(sth) {
    this.data = {
      sth,
      timestamp: new Date()
    }
  }

  create(createData) {
    const newData = Object.assign({}, this.theData, {
    /*      this getter seems to work ^^^^^^^^^^^^ */
      createData
    })
    console.log(newData) // looks good
    // set'ter new data
    this.theData = newData;
    return this
  }

  get theData() {
    return this.data
  }

  set theData(newData) {
    console.log('setting')
    this.data = newData;
  }
}

const Instance = new myClass('construct data')
  .create({createData: 'some data'})
atiq1589
  • 2,227
  • 1
  • 16
  • 24
3

this.theData(newData) would be accessing theData's getter. Since .data is not a function at the time that line executes (or ever), that is why you are getting that error.

To fix the problem, you should actually use the setter:

this.theData = newData;
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • I see. Thanks. This is preferred to directly setting the `this.data` value? Do you know why? – 1252748 Mar 14 '18 at 05:54
  • @1252748 That's a matter of opinion. See [here](https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors) for some discussion of the merits and demerits of using getters and setters. – JLRishe Mar 14 '18 at 05:59
  • Wow, took me an hour to find your valuable answer. Thanks a lot. – TheNickest Mar 29 '22 at 17:14