开发者

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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜