I want an object to overwrite itself using a setter. Unfortunately it does not work with my script. Probably it is because "this" cannot stand alone. Is there another way to solve this?
class myClass {
set updateObj(value) {
this = value // how to overwrite the object itself? "this" doesn't work ..
}
}
let myObject = new myClass()
const test = (myObject.updateObj = { foo: "bar" })
console.log(test)
CodePudding user response:
No an instance cannot replace itself.
But you can merge some data with properties into this
with Object.assign
.
class myClass {
set updateObj(value) {
Object.assign(this, value)
}
}
let myObject = new myClass()
myObject.updateObj = { foo: "bar" }
console.log(myObject)
myObject.updateObj = { foo: "baz" }
console.log(myObject)