I am working on GAS(Google Apps Script) where I use ES5 javascript.
I defined a class as follows:
var Test = function(a){
this._a = a;
}
Test.prototype.doSomething = function(){
//do something here
}
And then, I want to add setter and getter for this._a
in the same way as Test.prototype.doSomething is defined.
I found this code to define setter and getter in this link :
var o = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2
}
};
However, I don't know how to apply this way to my case.
Could you please tell me how? Thanks in advance.
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
});
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).
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.