无法分配给定义为可写的属性

Can't assign to 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??';

对对象属性的赋值总是对对象本身的局部"own"属性的赋值。原型上有一个同名 属性 的事实并不重要。您的实例是一个密封对象,因此您不能写入它。

如果你打电话给

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

你会没事的。

这似乎正是预期的行为。在此处查看文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal

Sealing an object prevents new properties from being added and marks all existing properties as non-configurable. This has the effect of making the set of properties on the object fixed and immutable

重要的一点是 "making the set properties on the object fixed and immutable"