Implementation of standard get and set accessors
Copy Code code as follows:
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 work correctly:
This may be true of our common implementation methods:
Copy Code code 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
Copy Code code as follows:
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'll now return to "beautiful body";
The following browsers work correctly:
Implementing accessors through Object.defineproperty
The future ECMAScript standard extended object method will be implemented through Object.defineproperty, which is why IE8 is the way to implement get and set accessors, it seems that Microsoft is still very far-sighted, unfortunately, only now 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.
The implementation of get and set accessors on DOM elements
Copy Code code as follows:
Object.defineproperty (document.body, "description", {
Get:function () {
return THIS.DESC;
},
Set:function (val) {
This.desc = val;
}
});
document.body.description = "Content container";
Document.body.description'll now return "Content container"
The following browsers work correctly:
Implementation of get and set accessors for normal objects
Copy Code code as follows:
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 "Another Island"
The following browsers work correctly:
This article summarizes
Although Microsoft's IE only supports object.defineproperty, there is no perfect implementation of get and set accessor, but we have seen IE has made great progress, especially the new JavaScript engine used by IE9, support HTML5 and CSS3, support hardware acceleration and so on, I believe that one day each browser can fully embrace the standard, bringing a perfect web world.
Reference documents:
1. Getters and setters with JavaScript
2. JavaScript Getters and Setters
Author: Dream