Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of Object.freeze() not freezing objects within the passed object?

Tags:

javascript

I was learning more about the methods of JavaScript's Object constructor on MDN and I noticed that the last sentence of Object.freeze's description reads:

Note that values that are objects can still be modified, unless they are also frozen.

A behavior like that seems like it should be opt-in. What exactly is the benefit of having to manually freeze a frozen object's objects recursively?

If I'm freezing an object, why would I want the objects inside of it to still be mutable?

like image 888
aleclarson Avatar asked Feb 18 '14 06:02

aleclarson


People also ask

What is the purpose of object freeze?

The Object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.

What is difference between object freeze and object seal?

Object. freeze() makes an object immune to everything even little changes cannot be made. Object. seal() prevents from deletion of existing properties but cannot prevent them from external changes.

What does freeze in Ruby do?

The freeze method in Ruby is used to ensure that an object cannot be modified. This method is a great way to create immutable objects. Any attempt to modify an object that has called the freeze method will result in the program throwing a runtime error. These coding examples will throw a runtime error.


1 Answers

I think if recursive is the default strategy, some complex Objects could not behave as expected. Think about following situation:

<div id="root">
    <div id="stem">
        <div id="leaf>
        </div>
    </div>
</div>

and for some reason I want to freeze the stem, so I wrote these code:

Object.freeze(document.getElementById('stem'));

If it freezes recursively, the leaf would be frozen too, and it seems OK: if I want to freeze the stem, I also want to freeze it's children.

But wait, note that stem has another property -- It has parentElement too. So what will happen? When I freeze stem, I also freeze stem.parentElement, and stem.parentElement.parentElement... This is never what I want.

like image 70
张实唯 Avatar answered Nov 15 '22 15:11

张实唯