George
George

Reputation: 2120

Preventing properties from being added to a JavaScript object

I basically just want to know if there's some standardized way to prevent methods/properties from being added to a JavaScript object?

As a c++ programmer it seems like you could end up with a lot of headaches trying to debug JavaScript code when it lets you add properties to an object on the fly, especially in large code bases.

Upvotes: 1

Views: 940

Answers (2)

Alexander O'Mara
Alexander O'Mara

Reputation: 60557

There is sort-of, the ES5.1 Object.freeze function can prevent new properties from being added, as well as prevent existing properties from changing.

Working Example:

var o = {
  a: 123
};
o.b = 456;

// Freeze the object.
Object.freeze(o);

// Log the object.
console.log(o);

// These do nothing, properties do not change and are not added.
o.b = 0;
o.c = 789;

// Log the object.
console.log(o);

That being said, JavaScript is a super dynamic language, so doing this extensively might be considered an anti-pattern.

If freeze is too limiting, other options include Object.preventExtensions, and Object.seal, depending on what you wish to prevent.

Alternately ES6 Proxy objects can offer more control over which properties can be added or modified.

Upvotes: 3

ceckenrode
ceckenrode

Reputation: 4703

Not really. There's probably ways to configure objects you don't want to be able to just attach new properties to, but nothing practical or standardized. Being primarily a javascript developer I don't find this to be an issue. I believe typescript does something for this with interfaces where it'll throw a warning if you start attaching properties it doesn't expect. A lot of javascript developers aren't a fan of this, but you might want to give it a try https://www.typescriptlang.org/docs/tutorial.html

Upvotes: 0

Related Questions