Object.seal 函数 freeze()方法冻结一个对象

本文介绍了JavaScript中用于锁定对象的方法:Object.seal() 和 Object.freeze()。Object.seal()阻止添加新属性并固定现有属性,而Object.freeze()进一步阻止了属性值的修改。通过示例展示了如何使用这些方法。

Object.seal 函数 (JavaScript)

阻止修改现有属性的特性,并阻止添加新属性。

语法

JavaScript

Object.seal(object)

参数

object

必需。在其上锁定特性的对象。

返回值

传递给函数的对象。

异常

如果 object 参数不是对象,则将引发 TypeError 异常。

ExceptionCondition

备注

Object.seal 函数执行以下两项操作:

  • 使对象不可扩展,这样便无法向其添加新属性。

  • 为对象的所有属性将 configurable 特性设置为 false

在 configurable 特性为 false 时,无法更改属性的特性且无法删除属性。在 configurable 为 false 且 writable 为 true 时,可以更改 value 和 writable 特性。

Object.seal 函数不更改 writable 特性。

var obj = { pasta: "spaghetti", length: 10 };
// Seal the object.
Object.seal(obj);
document.write(Object.isSealed(obj));
document.write("<br/>");

// Try to add a new property, and then verify that it is not added. 
obj.newProp = 50;
document.write(obj.newProp);
document.write("<br/>");

// Try to delete a property, and then verify that it is still present. 
delete obj.length;
document.write(obj.length);

// Output:
// true
// undefined
// 10

Object.freeze 函数 (JavaScript)

阻止修改现有属性的特性和值,并阻止添加新属性。

语法

JavaScript

Object.freeze(object)

参数

object

必需。在其上锁定特性的对象。

返回值

传递给函数的对象。

var obj = { pasta: "spaghetti", length: 10 };

// Freeze the object.
Object.freeze(obj);

// Try to add a new property, and then verify that it is not added. 
    obj.newProp = 50;
    document.write(obj.newProp);
    document.write("<br/>");

// Try to delete a property, and then verify that it is still present. 
delete obj.length;
document.write(obj.length);
document.write("<br/>");

// Try to change a property value, and then verify that it is not changed. 
obj.pasta = "linguini";
document.write(obj.pasta);

// Output:
// undefined
// 10
// spaghetti

转载于:https://my.oschina.net/shuaihong/blog/906350

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值