EDIT Oct 2016: Please note this question was asked in 2012. Every month or so someone adds a new answer or comment that refutes an answer, but doesn’t really make sense to do so as the question is probably out of date (remember, it was for Gnome Javascript to write gnome-shell extensions, not browser stuff, which is quite specific).
Following my previous question on how to do subclassing in Javascript, I’m making a subclass of a superclass like so:
function inherits(Child,Parent) { var Tmp = function {}; Tmp.prototype = Parent.prototype; Child.prototype = new Tmp(); Child.prototype.constructor = Child; } /* Define subclass */ function Subclass() { Superclass.apply(this,arguments); /* other initialisation */ } /* Set up inheritance */ inherits(Subclass,Superclass); /* Add other methods */ Subclass.prototype.method1 = function ... // and so on.
My question is, how do I define a setter/getter on the prototype with this syntax?
I used to do:
Subclass.prototype = { __proto__: Superclass.prototype, /* other methods here ... */ get myProperty() { // code. } }
But obviously the following won’t work:
Subclass.prototype.get myProperty() { /* code */ }
I’m using GJS (GNOME Javascript), and the engine is meant to be the more-or-less same as the Mozilla Spidermonkey one. My code is not intended for a browser so as long as it’s supported by GJS (I guess that means Spidermonkey?), I don’t mind if it’s not cross-compatible.
Advertisement
Answer
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); });