开发者

prevent access with setter

The problem is to prevent overriding from outside of a object.

my idea is to use setters:

var spot = function(val){
    this.id = val;
    this.__defineSetter__("id", function(val){alert("bang");});
}

The id should be set once in the constu开发者_如何学运维ctor and never be changed. I would also like to define the setter on the prototype because I have 10.000 spots. But in this case the setter prevets access also to the consructor.

I am not willing to use var id in the constructor and define a getter on it. In this case every single one of the (10.000) objects has its own closure.

A second question is: Can the setter somehow know wether the var is changed from the constructor or later from a (spot)internal function? So I could prevent access just from outside the object.


Firstly, that code is non-standard and deprecated. Depending on the platform you're developing for, I suggest using preventExtensions or freeze. Or maybe you just want to define the id property as read-only, in which case use defineProperty.

Secondly, as you've done things, each instance of spot already has it's own closure. That setter that you defined is a unique function + lexical scope that will exist for every spot, aka closure. So I'm not sure what the big deal is with making a getter as well. Although the first point trumps here, and you should be using the new methods to achieve that functionality.

Lastly, no matter what direction you take, the setter will not be able to "know" anything. So you can either have a separate variable, something to the tune of isInitialised, or create a code invariant so that the value is undefined at first, and numeric afterwards, which allows the simple check if the variable has a defined value, in which case it's been set, and shouldn't set it again.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜