js 深冻结 与 浅冻结 Object.freeze

时间:2023-08-03 09:44:44

1、深冻结

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js 深冻结 与 浅冻结</title>
</head>
<body>
<script type="text/javascript">
function deepFreeze(o) {
var prop, propKey
Object.freeze(o) // 首先冻结第一层对象
for (propKey in o) {
prop = o[propKey]
if (!o.hasOwnProperty(propKey) || !(typeof prop === "object") || Object.isFrozen(prop)) {
// 跳过原型链上的属性、基本类型和已冻结的对象.
continue
}
deepFreeze(prop) //递归调用.
}
}
</script>
</body>
</html>

2、浅冻结

Object.freeze(o)