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.
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;