Google Apps Script is an interesting dialect of JavaScript in that it is both very out of date (though I understand that's going to get fixed) and yet has the odd smattering of modern things in it.
There are a couple of older ways to do what you're trying to do, hopefully one of them works in GAS:
Object.defineProperty
This is still modern, but was added long enough ago GAS may have it: Using Object.defineProperty
, like this:
var Test = function(a){
this._a = a;
};
Test.prototype.doSomething = function(){
//do something here
};
Object.defineProperty(Test.prototype, "a", {
get: function() {
return this._a;
},
set: function(value) {
this._a = value;
},
configurable: true
});
Using get
and set
Syntax
...to define a getter and a setter, as in your example in the question.
var Test = function(a){
this._a = a;
};
Test.prototype = {
constructor: Test,
doSomething: function(){
//do something here
},
get a() {
return this._a;
},
set a(value) {
this._a = a;
}
};
Note that when you completely replace the object on the prototype
property like that, you want to be sure to define the constructor
property as shown above (it's defined that way by default in the object you get automatically, but if you replace it, naturally it's not automatically provided on the replacement).
The REALLY Old Way
I doubt GAS supports it, but just in case, the really old way to do it uses __defineGetter__
and __defineSetter__
like this:
var Test = function(a){
this._a = a;
};
Test.prototype.doSomething = function(){
//do something here
};
Test.prototype.__defineGetter__("a", function() {
return this._a;
});
Test.prototype.__defineSetter__("a", function(value) {
this._a = value;
});
This was never officially part of ECMAScript, but it was in the dialect of JavaScript from Mozilla for years (and probably still is, for backward compatibility).