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

Can't assign to property defined as writable

本文关键字:属性 定义 分配      更新时间:2023-09-26

我有这个代码片段,但无法弄清楚为什么在尝试为定义为可写的属性分配值时它会抛出错误:

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??';

对对象属性的赋值始终是对对象本身的本地"自己的"属性的赋值。原型上有一个同名属性这一事实并不重要。您的实例是密封对象,因此您无法写入它。

如果你要打电话

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

重要的一点是"使对象的集合属性固定且不可变"