js 禁止修改变量:冻结对象或数组 Object.freeze()

Object.freeze()的使用

数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Object.freeze</title>
</head>
<body>
<!--
https://juejin.cn/post/6844904142993883143
-->
<script>
let fruits = ["apple", "bananar", "ananas"]
Object.freeze(fruits)
fruits[0] = "aaaaa";
fruits[1] = "bbb";
console.log(fruits[0]);
console.log(fruits);
</script>
</body>
</html>

对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Object.freeze</title>
</head>
<body>
<script>
let people = {
name: "quanyi",
position: "developer",
age: 18
};

Object.freeze(people);
people.age = 12; // 可以修改f
console.log(people.age);

delete people.position;
console.log(people.position);

people.aa = "aa";
console.log(people);
</script>
</body>
</html>


js 禁止修改变量:冻结对象或数组 Object.freeze()
https://github.com/chergn/chergn.github.io/5b9aad55ef81/
作者
全易
发布于
2024年3月28日
许可协议