...
/Object.preventExtensions, seal, and freeze
Object.preventExtensions, seal, and freeze
Learn how Object.freeze and Object.seal are similar to Object.assign and help us implement functional programming. ES2015 adds the ability to truly freeze an object and make it immutable.
We'll cover the following...
In this lesson, we’ll cover three functions that allow us to enforce functional programming. Each of these functions makes our object inflexible to varying degrees. We can prevent property addition, or we can freeze an object entirely.
Object.preventExtensions
Preventing Extensions
This is a function that helps us approach immutability. Once it’s called on an object, we can’t add anything to it.
Deletions and changes are still allowed. Only property addition is forbidden.
const obj = {prop: 'value',};Object.preventExtensions(obj);obj.nextProp = 8; // failsconsole.log(obj); // -> { prop: 'value' }obj.prop = 4; // succeedsconsole.log(obj); // -> { prop: 4 }delete obj.prop; // succeedsconsole.log(obj); // -> {}obj.prop = 17; // since the property no longer exists, failsconsole.log(obj); // -> {}
Checking Extensibility
We have a utility method that tells us if an object is extensible or not: Object.isExtensible
.
const obj = {};console.log(Object.isExtensible(obj)); // -> trueObject.preventExtensions(obj);console.log(Object.isExtensible(obj)); // -> false
Locked Prototype
Object.preventExtensions
permanently locks an object’s prototype. Attempts to use Object.setPrototypeOf
or to change the __proto__
property directly result in an error.
const obj = {};Object.preventExtensions(obj);Object.setPrototypeOf(obj, {});//-> TypeError: #<Object> is not extensible
Configuration
Property attributes ...