Object.freeze()方法可以使对象不可变, 但是如果嵌套了对象,则无法防止可变性。Object.freeze()只能为外部父对象提供不变性 ,它不能访问任何内部子对象(嵌套)。
在下面的示例中,没有嵌套对象。Object.freeze() 方法将尝试冻结 整个对象。因此,即使在冻结对象之后,属性“名称”也没有变化。
<html> <body> <script> const person = { "name" : "Suresh", "Country" : "India", "Designation" : "Mayor" } document.write("Before freeze the name is" +" "+ person.name ); document.write("</br>"); Object.freeze(person); person.name = "John"; document.write("After freeze the name is" +" "+ person.name); </script> </body> </html>
输出结果
Before freeze the name is Suresh After freeze the name is Suresh
当嵌套对象被Object.freeze()尝试冻结时 ,结果是徒劳的,因为Object.freeze()无法访问嵌套对象。
在下面的示例中,即使使用 Object.freeze()方法冻结 了对象,嵌套对象的属性也会更改。
<html> <body> <script> const person = { "name" : "Suresh", "Country" : "India", "Designation" : "Mayor", "CompaniesOwned" :{ "Company1" : "Tesla", "Company2" : "SolarCity", "Company3" : "Spacex" } } document.write("Before freeze " + " " + "Company2 is" + " "+ person.CompaniesOwned.Company2); Object.freeze(person); document.write("</br>"); person.CompaniesOwned.Company2 = "Neuralica"; document.write("After freeze" + " " + "Company2 is" + " "+ person.CompaniesOwned.Company2); </script> </body> </html>
输出结果
Before freeze Company2 is SolarCity After freeze Company2 is Neuralica