civiltomain
civiltomain

Reputation: 1166

javascript. How to forbide object properties creation

I need a way to avoid create custom properties for an object.
This is my code:

object_to_instance = function () {
  this["elem1"] = 0;
  this["elem2"] = 0;
  // ....
  this["elem_n"] = 0;
}

my_obj = new object_to_instance();
my_obj.elem1 =7;

What I want is a way to avoid that :

my_obj.ele2 = 8 // (The m of elem2 is missing)  

could be possible.

Now I have a ele2 property but I'd want an error!

Also, using strict mode does not help.

Any ideas ?

Upvotes: 1

Views: 54

Answers (1)

apsillers
apsillers

Reputation: 115950

You likely want Object.preventExtensions:

The Object.preventExtensions() method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object).

Simply call Object.preventExtensions(my_obj) whenever you want to lock the properties.

Unlike Object.seal, this will still allow existing properties to be deleted.

Note that this will only work in modern browers; in particular, IE 8 and below do not support it.

Upvotes: 1

Related Questions