I've been looking over the GNOME shell javascript interface and noticed the following snippet (popupMenu.js
for those who are interested) from the prototype of a class:
PopupSwitchMenuItem.prototype = {
__proto__: PopupBaseMenuItem.prototype,
_init: function(text, active, params) {
... (code)
},
... function definitions
get state() {
return this._switch.state;
},
... more functions
};
Could anyone explain to me what the get state() { ... }
means? I thought everything had to be of the form name: value
within a javascript object? (If I make one of these objects I can do obj.state
which returns what I assume is this._switch.state
).
It may help to note that GNOME say they use a flavour of javascript (gjs) similar to Mozilla's Spidermonkey, so is this behaviour a non-standard javascript behaviour and a feature of spidermonkey/gjs?
Also, is there documentation pertaining to this?
Check out https://developer.mozilla.org/en/JavaScript/Reference/Operators/get and John Resig's post at http://ejohn.org/blog/javascript-getters-and-setters/
The interesting thing is that you access the properties just like any other property, except they are dynamically created... in example
foo = {
get blah() {
return "bar";
}
}
foo.blah == "bar"
Without native getters you would have to do foo.blah()
. Frankly I've never used them simply because IE8 doesn't support it, and the advantage is just so minor. Most commonly I can see them being useful in a situation where I started with a "dumb" property like foo.blah, and at some point later in the development cycle realized that I wanted foo.blah(), and had to do the conversion at every point, while with the getters and setters such a conversion is unneccessary, since you simply change the object definition.