How to define setter/getter on prototype
Using an object literal declaration (simplest way):
var o = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2
}
};
Using Object.defineProperty
(on modern browsers that support ES5):
Object.defineProperty(o, "myProperty", {
get: function myProperty() {
// code
}
});
Or using __defineGetter__
and __defineSetter__
(DEPRECATED):
var d = Date.prototype;
d.__defineGetter__("year", function() { return this.getFullYear(); });
d.__defineSetter__("year", function(y) { this.setFullYear(y); });
Use Object.defineProperty()
on Subclass.prototype
. There are also __defineGetter__
and __defineSetter__
available on some browsers, but they are deprecated. For your example, it would be:
Object.defineProperty(Subclass.prototype, "myProperty", {
get: function myProperty() {
// code
}
});