Help us understand the problem. What is going on with this article?

[GAS] GogleAppsScriptでClassもどき!

More than 1 year has passed since last update.

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です。
(が、大してまともなことも返せない可能性大です。すいません。)

s_maeda_fukui
目指せ!カイゼンマスター!(マーケティング・エンジニア営業企画もどき) 高専・電子情報卒→大学文転→CRMマーケター(スクラムマスター取れた。)
leverages
インターネットを事業軸に、IT、医療、その他新規分野に30を超える自社メディア事業を展開しています。
https://leverages.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした