How to create Object constant in javascript

Asked

Viewed 38 times

2

I want to create Object that cannot be altered, redefined or removed. The aim is to make it possible for objects not to be altered by accident or intentionally.

2 answers

1


By combining writable:false and configurable:false, you can essentially create a constant (it cannot be altered, redefined or removed) as an object property, such as:

var myObject = {};

Object.defineProperty( myObject, "FAVORITE_NUMBER", {
    value: 42,
    writable: false,
    configurable: false
} );

But this does not guarantee that they can add new properties to the object.

If you want to prevent an object from having new properties added to it, keeping only the rest of the object’s properties, call Object.preventExtensions(..):

var myObject = {
    a: 2
};

Object.preventExtensions( myObject );

myObject.b = 3;
myObject.b; // undefined

In the non-strict mode creating b fails silently. No Strict mode is released a TypeError.

1

You can use a proxy to observe modifications to the object, and if there is an error:

function createConstant(obj) {
    return new Proxy(obj, {
        set() {
            throw new Error("You cannot change the object.");
        }
    });
}

const obj = createConstant({a: 1});
obj = {}; // Error
obj.a = 1; // Error
obj.b = 1; // Error
obj.a = null // Error
obj = null // Error

Remembering that yes the variable can still be removed by the memory manager, if this is unwanted you will have to create this variable within the global object. Do not recommend, the ideal is to try to behave to the scopes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.