Classとは
みたいな本格的なことは、誰かに任せるとして。
GASは、JSのバージョンが古いらしく
prototypeに入れてくのが旧JSのclass実装
する必要がある。
(Pythonとかめっちゃ楽なのに・・・。ま、JSのせいではないか。)
やってみた
var Human = function(name, height, weight) {
this.name = name;
this.height = height;
this.weight = weight;
};
Human.prototype.sayHello = function() {
Logger.log("Hello I'm " + this.name);
};
// BMIをセット
Human.prototype.setBMI = function() {
Logger.log('setBMI')
m_height = this.height/100;
bmi = this.weight / (m_height * m_height)
this.bmi = bmi;
};
// BMIを叫ぶ
Human.prototype.sayBMI = function() {
Logger.log('sayBMI')
if (this.bmi) {
Logger.log('My BMI score is ' + this.bmi);
} else {
this.setBMI();
Logger.log('My BMI score is ' + this.bmi);
}
};
// 体重を変える
Human.prototype.changeWeight = function(diff) {
this.weight = this.weight + diff;
}
main.js
function main() {
var
satoshi = new Human('satoshi', 160, 75),
masami = new Human('masami', 152, 54)
;
satoshi.sayHello()
masami.sayHello()
Logger.log('---')
masami.sayBMI()
masami.changeWeight(-3)
masami.setBMI()
masami.sayBMI()
Logger.log('---')
satoshi.sayBMI()
}
結果は、こう!
> Hello I'm satoshi
> Hello I'm masami
> ---
> sayBMI
> setBMI
> My BMI score is 23.372576177285318
> setBMI
> sayBMI
> My BMI score is 22.07409972299169
> ---
> sayBMI
> setBMI
> My BMI score is 29.296874999999993
嬉しいこと
使いまわしが楽になる。
オブジェクトに対して、プロパティとメソッド持たせられるのは便利。
補足
完全初心者が、使えればOKだろ、レベルでやってみたやつです。
マサカリ飛ばしてもらってもOKです。
(が、大してまともなことも返せない可能性大です。すいません。)