Skip to content Skip to sidebar Skip to footer

Not Able To Update A Class Property In ES6

How does this translate to ES6? I've tried this: But it doesn't work because the class properties are actually attached directly to the instanciated object instead of being attac

Solution 1:

It seems an antipattern to me to change the prototype. But if you really want this, you should just continue to use the same syntax as before for defining the property:

class Mock { }
Mock.prototype.foo = "bar";

const obj = new Mock();
console.log(obj.foo);
Mock.prototype.foo = "Something else";
console.log(obj.foo);

Solution 2:

  • Because in ES6, the .prototype property of classes is not writable and not configurable
  • If you wanna change then use Object.defineProperty

    class Mock {
      foo = 'bar'
    }
    const obj = new Mock()
    console.log(obj.foo)
    
    Object.defineProperty(obj, 'foo', {
      value: 'Something else',
      writable: true,
      enumerable: false,
      configurable: false
    })
    
    console.log(obj.foo)

Post a Comment for "Not Able To Update A Class Property In ES6"