Home > Mobile >  Cannot redefine property in NodeJS (tho can in browser)
Cannot redefine property in NodeJS (tho can in browser)

Time:01-16

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

CodePudding user response:

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

  • Related