如何在 JavaScript 中冻结一个对象?


在现实世界中,javascript 没有像在其他语言中看到的传统类。它具有对象和构造函数。 Object.freeze() 是许多构造函数方法中的一种,有助于冻结对象。

冻结对象不允许将新属性添加到该对象,也阻止了该对象更改其自身属性。Object.freeze() 将始终尝试保留对象的枚举性、可配置性、可写性和原型。它不会创建冻结的副本。

应用程序

1) freeze() 用于冻结对象和数组。

2) freeze() 用于将对象设置为不可变。

语法

Object.freeze(obj)

示例

实时演示

<html>
<body>
<script>
// an object is created and a value is assigned
   var myObj1 = {
                prop1: 'freezed values can not be changed'
                };

// the created object is freezed
   var myObj2 = Object.freeze(myObj1);

// property of the frozen object is updated
   myObj2.prop1 = 'change the freezed value';

// Displaying the properties of the frozen object -->
   document.write(myObj2.prop1);

</script>
</body>
</html>

输出
freezed values can not be changed

更新于:2019 年 7 月 30 日

已阅读 118 次

开启 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.