tags:

views:

57

answers:

3

Hey all,

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

+3  A: 

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

cletus
Aww.. well thanks for the response!
Matt
+2  A: 

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...

anthonyv
That's too bad. Thanks for your response!
Matt
+1  A: 

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 :)

Crescent Fresh
Ohh interesting! I'm not up with the whole EMCAScript stuff, but is that the new specs for the javascript interpreter?
Matt
@Matt: yes, JavaScript engines will be integrating features of ECMAScript 5 in time. There is no public ECMAScript 5 implementation that I know of.
Crescent Fresh