开发者

Dynamic property getters/setters in Javascript?

Storage (localStorage, sessionStorage) allows using arbitrary properties. E.g. you can do

localStorage.foo = 'bar';

instead of

localStorage.setItem('foo', 'bar');

Can my own javascript objects have the same behavior? I want to execute some code, when a property is attempted to be set.

Note: I obviously know I can create setters, but that won't work for properties whose names I don't know in advance.

Note #2: After a bit of examination of the spec, I see that it doesn't really guarantee that this will work, unless the key was already set with setItem():

The names of the supported named propert开发者_如何学运维ies on a Storage object are the keys of each key/value pair currently present in the list associated with the object

I could probably achieve this behavior myself too, as long as the first set goes through a method, by dynamically defining getters/setters.


You can use __defineGetter__() and __defineSetter__(), but unfortunately they're Mozilla extension to Javascript 1.5, so they're only available in some browsers (recent versions of Firefox, Opera and Safari).

More information and some examples here.

Other than this, there is no way to add custom behaviour to setting/getting properties on an object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜