Object.freeze vs Object.seal vs Object.preventExtensions
In my last post I talked about making entire objects extensible instead of just a variable using Object.freeze. This is actually the most strict way of making object immutable. There are 2 other ways: Object.seal and Object.preventExtensions. Essentially, Object.freeze is a superset of Object.seal which is a superset of Object.preventExtensions. It is best to demonstrate this in an example.
var attempt = function(callback) { try { callback(); } catch (e) {} }; var obj = Object.preventExtensions({ property1: 'value1', property2: 'value2', property3: 'value3' }); obj.property1 = 'value1 EDITED'; attempt(function() { obj.property3 = 'value3' });// can't extend delete obj.property3; Object.defineProperty(obj, 'property2', { get: function() { return 'test' } }); console.log(obj); // { property1: 'value1 EDITED', property2: [Getter] } var obj2 = Object.seal({ property1: 'value1', property2: 'value2', property3: 'value3' }); obj2.property1 = 'value1 EDITED'; attempt(function() { obj2.property3 = 'value3' });// can't extend attempt(function() { delete obj2.property3 });// can't delete attempt(function() { Object.defineProperty(obj2, 'property2', { get: function() { return 'test' } }); });// can't changing property definitions console.log(obj2); // { property1: 'value1 EDITED', // property2: 'value2', // property3: 'value3' } var obj3 = Object.freeze({ property1: 'value1', property2: 'value2', property3: 'value3' }); attempt(function() { obj3.property1 = 'value1 EDITED' }); attempt(function() { obj3.property3 = 'value3' });// can't extend attempt(function() { delete obj3.property3 });// can't delete attempt(function() { Object.defineProperty(obj3, 'property2', { get: function() { return 'test' } }); });// can't changing property definitions console.log(obj3); // { property1: 'value1', property2: 'value2', property3: 'value3' }
So the only difference difference between Object.seal and Object.freeze is that seal does allow properties to be changed. Note that the attempt was used to clarify the example code and in general errors should not be hidden like that. Finally, here is a table giving a clear explanation.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/sealAndPreventExtensions.js













