What we're going to share with you today is the get and set accessors in JavaScript, which are very similar to the accessors in C #.
Implementation of the 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'll now return "Test2"
The following browsers will work correctly:
The implementation method that we commonly use may be this:
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 would now return "Beautiful body";
The following browsers will work correctly:
Implementing accessors through Object.defineproperty
The future method of ECMAScript the standard extension objects will be implemented through Object.defineproperty, which is why IE8 is the way to implement get and set accessors, it seems that Microsoft is very visionary, unfortunately, there is only ie8+ and chrome 5.0+ support, other browsers are not supported, and ie8+ only supports DOM elements, but future versions will support normal 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 would now return "Content container"
The following browsers will work correctly:
Implementation of get and set accessors for ordinary 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'll now return to "another island"
The following browsers will work correctly:
This paper summarizes
Although Microsoft's IE only supported the object.defineproperty, there is no perfect implementation of get and set accessors, but we have seen that IE has made great progress, especially the newly released IE9 use of the new JavaScript engine, Support HTML5 and CSS3, support hardware acceleration and so on, I believe that one day each browser can fully embrace the standard, bring a perfect web world.
Reference documents:
1. Getters and setters with JavaScript
2. JavaScript Getters and Setters
Source: http://www.cnblogs.com/lhb25/archive/2010/09/19/1830724.html
Get and set accessors in JavaScript