четверг, 29 сентября 2011 г.

Getters And Setters With JavaScript – Code Samples And Demos


Not many people know it, but you can use “real” getters and setters in JavaScript if you want to.

De-Facto Offerings

Firefox 2.0+, Safari 3.0+, Google Chrome 1.0+ and Opera 9.5+ support a de-facto way of getters and setters:
01.var lost = {
02.loc : "Island",
03.get location () {
04.return this.loc;
05.},
06.set location(val) {
07.this.loc = val;
08.}
09.};
10.lost.location = "Another island";
11. 
12.// lost.location will now return "Another island"
And on DOM elements:
01.HTMLElement.prototype.__defineGetter__("description"function () {
02.return this.desc;
03.});
04.HTMLElement.prototype.__defineSetter__("description"function (val) {
05.this.desc = val;
06.});
07.document.body.description = "Beautiful body";
08. 
09.// document.body.description will now return "Beautiful body";

Via Object.DefineProperty

The future, and ECMAScript standardized way, of extending objects in all sorts of ways is throughObject.defineProperty. This is how Internet Explorer chose to implement getters and setters, but it is unfortunately so far only available in Internet Explorer 8, and not in any other web browser. Also, IE 8 only supports it on DOM nodes, but future versions are planned to support it on JavaScript objects as well.
Getter and setters in IE8+:
01.Object.defineProperty(document.body, "description", {
02.get : function () {
03.return this.desc;
04.},
05.set : function (val) {
06.this.desc = val;
07.}
08.});
09.document.body.description = "Content container";
10. 
11.// document.body.description will now return "Content container"

Test Cases

Conclusion

Kudos for Microsoft to take the step to implement Object.defineProperty, although it’s sad that it’s only available for DOM elements as of now. Also, just as we have consistency between web browsers with innerHTMLXMLHTTPRequest etc, it would have been really desirable if Microsoft would have supported the several years-old de-facto way of implementing getters and setters.
So, Microsoft slowly treads forward, which is good, but at the same unfortunately gives us yet another case of doing something different to make it work in Internet Explorer (more about this can be read inECMAScript getters and setters interoperability).
Anyway, getters and setters are here today, and with some feature detection, you can use it to implement some nice things. Happy coding! :-)

Комментариев нет: