Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 class setter is not recognized as a function

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?

like image 256
1252748 Avatar asked Nov 15 '25 12:11

1252748


2 Answers

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'})
like image 88
atiq1589 Avatar answered Nov 18 '25 17:11

atiq1589


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;
like image 44
JLRishe Avatar answered Nov 18 '25 17:11

JLRishe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!