Search code examples
javascriptecmascript-5

Can't assign to property defined as writable


I have this snippet, but can't figure why it throws an error when trying to assign a value to a property defined as writable:

function Constructor()
{
    Object.seal(this);
}

Object.defineProperties(Constructor.prototype,
{
  field: {value: null, writable: true}
});


var instance = new Constructor();

instance.field = 'why this doesn\'t work??';

Solution

  • Assignments to object properties are always assignments to local "own" properties of the object itself. The fact that there's a like-named property on the prototype doesn't matter. Your instance is a sealed object, so you can't write to it.

    If you were to call

    Object.getPrototypeOf(instance).field = "this works";
    

    you'd be OK.