Class ファイル

【実行画面】

【Source Code】
ClassFile.html のソースコードです。
<script src="gcmlcm_class.js" type="text/javascript"></script>
</head>

<body>
<h1>Class File</h1>

【実行画面】
<script type="text/javascript">
  var cls = new gcmlcm(32, 24);
  ans = cls.gcm();
  document.write("GCM(32,24): ", ans, " <br>");
  ans = cls.lcm();
  document.write("LCM(32,24): ", ans, " <br>");
</script>

汎用の Class File を作成してソースコードを組み込む方法が良く使われます。
試しに GCM, LCM を計算する gcmlcm_class.js を使ってみましょう。
<head> の中で gcmlcm_class.js を取り込みます。
<script src="gcmlcm_class.js" type="text/javascript"></script>
</head>

Class の使い方は Javascript の gcmlcm Class と同じです。
<script type="text/javascript">
  var cls = new gcmlcm(32, 24);
  ans = cls.gcm();
  document.write("GCM(32,24): ", ans, " <br>");
  ans = cls.lcm();
  document.write("LCM(32,24): ", ans, " <br>");
</script>

【gcmlcm_class.js Source Code】
gcmlcm_class.js のソースコードです。
this. で始まるのが gcmlcm クラスの内部変数と内部メソッドです。
GCM(最大公約数), LCM(最小公倍数)の説明は Gcm Lcm の説明 を参照して下さい。
function gcmlcm(n, m)
{   this.n = n;     //値1
    this.m = m;     //値2
    this.nm = n * m;
    this.gcm = function()
    {   while(this.n!=this.m)
        {   if (this.n>this.m)	this.n -= this.m;
            else	this.m -= this.n;
        }
        return this.n;
    }
    this.lcm = function()
    {   w = this.gcm();
        return this.nm / w;
    }
}

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