Matt
Matt

Reputation: 22921

Prevent ability to add "instance variables" dynamically Javascript OOP

I was wondering if there is a way to disallow the following in javascript:

var c = new Circle(4);
c.garbage = "Oh nooo!"; // Prevent this!!

Any ideas?

EDIT: I was just about to give up on this, but I decided to check to see what the gods do (jQuery dev team).. how do they accomplish this?

$('#Jimbo').hello = "hi!";
alert($('#Jimbo').hello); // undefined

EDIT 2: Stupid mistake.. If you do this:

var hi = $('#Jimbo');
hi.hello = "hi!";
alert(hi.hello); // You get "hi!"

Thanks, Matt Mueller

Upvotes: 2

Views: 264

Answers (3)

Crescent Fresh
Crescent Fresh

Reputation: 117008

ECMAScript 5 defines Object.preventExtensions which can prevent new properties from being added to your precious object:

var c = new Circle(4);
Object.preventExtensions(c); // prevents new property additions on c
c.garbage = "Oh nooo!"; // fail

The spec also defines Object.seal, and Object.freeze which prevent property deletion and property mutation (respectively). More info here and in ECMA-262, 5th edition (pdf).

Of course, this is of no current significance to you at all, but is exactly what you're after :)

Upvotes: 2

anthonyv
anthonyv

Reputation: 2465

As far as I know (and I could be wrong)... There is no way to prevent this. That the point of having a 'dynamic' language... if someone makes a typo or adds on a random field then thats life...

Upvotes: 2

cletus
cletus

Reputation: 625307

No there isn't. Javascript allows members to be dynamically added and there isn't a hook to prevent it.

Upvotes: 4

Related Questions