Javascript – How to define setter/getter on prototype

gettergjsjavascript

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.

Best Answer

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
    }
});