Reputation: 31815
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
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
Reputation: 708
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