Guerric P
Guerric P

Reputation: 31815

Not able to update a class property in ES6

How does this translate to ES6?

function Mock() { };
Mock.prototype.foo = 'bar';
var obj = new Mock();
console.log(obj.foo);
Mock.prototype.foo = 'Something else';
console.log(obj.foo);

I've tried this:

class Mock {
  foo = 'bar';
}
const obj = new Mock();
console.log(obj.foo);
Mock.prototype.foo = 'Something else';
console.log(obj.foo);

But it doesn't work because the class properties are actually attached directly to the instanciated object instead of being attached to Mock.prototype.

Upvotes: 1

Views: 1052

Answers (2)

trincot
trincot

Reputation: 350345

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

Upvotes: 2

Himanshu Pandey
Himanshu Pandey

Reputation: 708

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

Upvotes: 0

Related Questions