JavaScript の BMI Class

【実行画面】
  1. 【BMI Class の定義】
    <script type="text/javascript">
    function BMI(height, weight, gender)
    {   this.Height = Number(height)/100;   //身長
        this.Weight = Number(weight);       //体重
        this.Gender = gender;               //性別
        this.Bmi = parseInt(this.Weight / (this.Height * this.Height));
    
        this.Disp = function()
        {   var str= "身長:" + this.Height + " 体重:" + this.Weight + "  BMI: " + this.Bmi + "<br>\n";
            return str;
        }
        this.Msg = function()
        {   var str= "18.5以上25.0未満が標準です。";
            if (this.Gender==0) str= str + "男性の理想値は22.0です。 BMI: " + this.Bmi + "<br>\n";
            else    str= str + "女性の理想値は21.0です。 BMI: " + this.Bmi + "<br>\n";
            return str;
        }
    }
    </script>
    </head>
    
  2. 【実行画面のソースコード】
    <script type="text/javascript">
      var cls = new BMI(160, 64, 0);
      document.write(cls.Disp());
      document.write(cls.Msg(), "<br>\n");
    
      var cls = new BMI(155, 54, 1);
      document.write(cls.Disp());
      document.write(cls.Msg());
    </script><br>
    
  3. JavaScript では Object と Class は別物で、今度は Class(BMI) の説明です。
    var cls = new BMI(160, 64, 0); で BMI Class を生成します。
    このとき Constructor で「身長,体重,性別」を受け取ります。
    this は現在(BMI Class が呼ばれたとき)のインスタンスです。
    this. で始まるのは、クラスの内部変数と内部関数(メソッド)です。
    身長は単位がメートルなので100で割っています。
    <script type="text/javascript">
    function BMI(height, weight, gender)
    {   this.Height = Number(height)/100;   //身長
        this.Weight = Number(weight);       //体重
        this.Gender = gender;               //性別
        this.Bmi = parseInt(this.Weight / (this.Height * this.Height));
    
  4. BMI を計算する this.Disp() 関数です。
        this.Disp = function()
        {   var str= "身長:" + this.Height + " 体重:" + this.Weight + "  BMI: " + this.Bmi + "<br>\n";
            return str;
        }
    
  5. メッセージを作成する this.Msg() 関数です。
        this.Msg = function()
        {   var str= "18.5以上25.0未満を標準です。";
            if (this.Gender==0) str= str + "男性の理想値は22.0です。 BMI: " + this.Bmi + "<br>\n";
            else    str= str + "女性の理想値は21.0です。 BMI: " + this.Bmi + "<br>\n";
            return str;
        }
    </script>
    
  6. BMI Class の使い方です。
    var cls = new BMI(160, 64, 0); で Class を生成します。
    document.write(cls.Disp()); と document.write(cls.Msg(), "<br>\n"); で印字します。
    男性に続いて女性も試してみました。
    <script type="text/javascript">
      var cls = new BMI(160, 64, 0);
      document.write(cls.Disp());
      document.write(cls.Msg(), "<br>\n");
    
      var cls = new BMI(150, 54, 1);
      document.write(cls.Disp());
      document.write(cls.Msg());
    </script><br>
    

前田稔の超初心者のプログラム入門
超初心者のプログラム入門(JavaScript)