Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can an object overwrite itself using setter?

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading