Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new objects from frozen parent objects

This example creates an object, freezes it, and then creates a new object from the frozen object. If the second object tries to change the test property, it can't. It remains frozen with the first object's value of 10.

//Create an object and freeze it

var first = {
    test: 10
};
Object.freeze(first);

//Create a second object from the first one and
//try and change the new test property (you can't)

var second = Object.create(first);
second.test = 20;
console.log(second.test); //10

Here are my questions:

Is second.test a new property on a new object, or is it just a reference to the property in the frozen first object?
Is it possible to use the frozen first.test as a default value, but let second.test overwrite it if it needs to?

My reason for asking is because I want to make an immutable a base object as a template with default values, and then use it to make new objects that I can customize. What's the best approach for this?

Thanks!

like image 363
d13 Avatar asked Oct 31 '13 04:10

d13


People also ask

How do you make an object freeze?

Object.freeze() Method freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.

What's the difference between object seal and object freeze methods?

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 is object freeze ()?

freeze() The Object. freeze() method freezes an object. Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.


1 Answers

second is in fact a new object, with first being the prototype of second. The reason why

second.test = 20;

does not work is because upon assignment, it will look for the settings on the prototype (i.e. configurable, enumerable, writable, [[Extensible]]) and not assign to the instance if any of these are false1. To assign directly to the instance, you'll have to use Object.defineProperty on second:

var first = {
    test: 10
};
Object.freeze(first);

var second = Object.create(first);
Object.defineProperty(second, 'test', { value: 20, enumerable: true, configurable: true, writable: true });
console.log(second.test); // 20

1: [[Put]]: the ECMAScript Specification, §8.12.5

like image 122
Qantas 94 Heavy Avatar answered Oct 10 '22 16:10

Qantas 94 Heavy