JavaScript-Object.Freeze() & deepFreeze()
在 ES6 中,我們可以把變數宣告為常數const來使其不能被修改。
要阻止一個物件包含內部成員被修改可以視需求使用Object.freeze()或deepFreeze()來解決這個問題。
以下介紹兩種不同使用方法的程式碼範例提供參考。
使用Object.freeze來保護物件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const obj = { num: 10, obj: { content: "mutable object" } } Object.freeze(obj); obj.num = 5; obj.obj = { content: "changed!" } console.log(obj);
Output: { num: 10, obj: { content: "changed!" } }
|
obj.num不可更改,但obj.obj仍然可以被更改
MDN 提供 deepFreeze:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function deepFreeze(object) { // Retrieve the property names defined on object var propNames = Object.getOwnPropertyNames(object)
// Freeze properties before freezing self
for (let name of propNames) { let value = object[name]
object[name] = value && typeof value === "object" ? deepFreeze(value) : value }
return Object.freeze(object) }
|
1 2 3 4 5 6 7 8 9 10 11
| const obj = { num: 10, obj: { content: "mutable object" } } deepFreeze(obj); obj.num = 5; obj.obj = { content: "changed!" } console.log(obj);
|
Output:
1 2 3 4 5 6 7 8
| { num: 10, obj: { content: "mutable object" } }
|