4

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There's also new ECMAScript 5 getters and setters, currently making their way into new browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.