开发者

Indexed properties in javascript

开发者 https://www.devze.com 2023-02-17 09:34 出处:网络
(I can\'t believe this isn\'t possible, but I\'m probably not using the right search terms) I have a \'class\' like this:

(I can't believe this isn't possible, but I'm probably not using the right search terms)

I have a 'class' like this:

function MyClass() = {
    this.getItem = function(key) {
        // return whatever;
    };
    this.setItem = function(key, val) {
        // set whatever
    };
};

Is t开发者_StackOverflow中文版here someway that I can get/set via (what I think is called) an indexed property?

var test = new MyClass();
test["key"] = "value";
alert(test["key"]);

(Context, if it makes any difference, I'm trying to wrap localStorage in a class which adds a prefix to all keys. Wrapping setItem/getItem is easy. I just wanted to go further and wrap the [] functionality)


You don't have automatic accessors in that way in JavaScript. At least I've never seen it.

You could use

var test = new MyClass();
test.key = "value";
alert(test.key);

and

alert(test["key"]);

But that's maybe not what you're after...


As described in the MDC (link) it's possible to do this in Javascript 1.8.5. However support for this is poor and mostly only in firefox. Other than this there is no real way to do this.


It sounds like you are looking for getter and setters, which you read more about here:

https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects#Defining_Getters_and_Setters

Beware that this syntax is not supported in all browsers.

You can read more about getters and setters here:

http://ejohn.org/blog/javascript-getters-and-setters/

http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

0

精彩评论

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

关注公众号