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

Cannot redefine property in NodeJS (tho can in browser)

I’d like to redefine an existing property inside a class (it’s for experimenting purposes, I know I shouldn’t).

For some reason, the following code works in browser (Chrome), but not Node.js (v18.12.0).

function re(instance, name, val){
      let _value = val;
      Object.defineProperty(instance, name, {
           get: () => { return _value },
           set: (v) => { return _value = v }
      })
      return val;
}

class A {
    prop = re(this, 'prop', 456)
}

const a = new A()
console.log(a.prop)

Chrome console output would be 456, but node will be like nope, no redefining today, instead take this: TypeError: Cannot redefine property: prop. Which is sad. I tested on my pc plus at some online nodejs interpreter (replit.com).

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

>Solution :

You need to provide configurable attribute.

function re(instance, name, val){
      let _value = val;
      Object.defineProperty(instance, name, {
           get: () => { return _value },
           set: (v) => { return _value = v },
           configurable: true
      }, )
      return val;
}

class A {
    prop = re(this, 'prop', 456)
}

const a = new A()
console.log(a.prop)

You can refer to the MDN documentation here.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_redefine_property

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