The IE9 Beta version was released two days ago. It is really good news for those who are engaged in Web development. I hope all browsers will follow the same standards one day. Today I want to share with you the Get and Set accessors in JavaScript, which are very similar to those in C.
Standard Get and Set accessors
function Field(val){ this.value = val; } Field.prototype = { get value(){ return this._value; }, set value(val){ this._value = val; }};var field = new Field("test");field.value="test2";//field.value will now return "test2"
The following browsers can work properly:
Our common implementation methods may be as follows:
function Field(val){ var value = val; this.getValue = function(){ return value; }; this.setValue = function(val){ value = val; };}var field = new Field("test");field.setValue("test2")field.getValue() // return "test2"
Implementation of Get and Set accessors on DOM elements
HTMLElement.prototype.__defineGetter__("description", function () { return this.desc; }); HTMLElement.prototype.__defineSetter__("description", function (val) { this.desc = val; }); document.body.description = "Beautiful body"; // document.body.description will now return "Beautiful body";
The following browsers can work properly:
Implement accessors through Object. defineProperty
In the future, the ECMAScript standard extension Object method will use the Object. defineProperty is implemented, which is why IE8 implements get and set accessors through this method. It seems that Microsoft is still far-sighted. Unfortunately, only IE8 + and Chrome 5.0 + support is supported currently, other browsers are not supported, and IE8 + only supports DOM elements. However, in future versions, it will support common Javascript objects like Chrome.
Implementation of Get and Set accessors on DOM elements
Object.defineProperty(document.body, "description", { get : function () { return this.desc; }, set : function (val) { this.desc = val; } }); document.body.description = "Content container"; // document.body.description will now return "Content container"
The following browsers can work properly:
Implementation of Get and Set accessors for common objects
var lost = {loc : "Island"};Object.defineProperty(lost, "location", {get : function () {return this.loc;},set : function (val) {this.loc = val;}});lost.location = "Another island";// lost.location will now return "Another island"
The following browsers can work properly:
Summary
Although Microsoft's IE only supports Object. defineProperty has no perfect Get and Set accessors, but we have seen a lot of progress in IE, especially the new javascript Engine Used in IE9, it supports HTML5 and CSS3, hardware acceleration, and so on. I believe that one day each browser will embrace the standard and bring a perfect WEB world.
References:
1. Getters and setters with JavaScript
2. JavaScript Getters and Setters