Object.preventExtensions()
方法阻止向对象添加新属性。
示例
const obj = { x: 1, y: 2 };
// prevent the object from having new properties added to it
Object.preventExtensions(obj);
// try to add a new property to the object
obj.z = 3;
console.log(obj);
// Output: { x: 1, y: 2 }
preventExtensions() 语法
preventExtensions()
方法的语法是
Object.preventExtensions(obj)
这里,preventExtensions()
是一个静态方法。因此,我们需要使用类名 Object
来访问该方法。
preventExtensions() 参数
preventExtensions()
方法接受
- obj - 应设为不可扩展的对象
preventExtensions() 返回值
preventExtensions()
方法返回 obj,即被设为不可扩展的对象。
注意事项
- 不能再向其添加新属性的对象称为不可扩展对象。
- 通常,不可扩展对象的属性仍然可以被删除。
- 尝试向不可扩展对象添加新属性将失败,可能会默默失败,或者在严格模式下抛出
TypeError
。 - 仍然可以将属性添加到不可扩展对象的原型中。
示例:Javascript Object.preventExtensions()
// create an empty object
let obj = {};
// add a property to the object
Object.defineProperty(obj, "name", {
value: "Smith",
});
// print object
console.log(obj.name);
// prevent adding of new property to the object
Object.preventExtensions(obj);
// add another property to the object
Object.defineProperty(obj, "age", {
value: 26,
});
// print object
console.log(obj.age);
输出
Smith Object.defineProperty(obj, "age", { ^ TypeError: Cannot define property age, object is not extensible
在上面的示例中,我们使用 preventExtensions()
方法来阻止向 obj 对象添加新属性。
首先,我们创建了一个空对象 obj,并使用 defineProperty() 方法将 name 属性添加到对象中。
// Output: Smith
console.log(obj.name);
上面的代码输出 Smith
,这意味着 name 已添加到对象中。
然后,我们使用 preventExtensions()
方法将 obj 设为不可扩展。
Object.preventExtensions(obj);
最后,我们尝试在 obj 上定义一个新属性 age,这会导致 TypeError
。
Object.defineProperty(obj, "age", {
value: 26,
});
另请阅读