Javascript の Class の領域

【実行画面】

【Source Code】
<script type="text/javascript">
function test(n)
{
  n1 = n+1;
  var n2 = n+2;
  this.n3 = n+3;
  test.n4 = n+4; 
  this.type = function()
  {
    document.write("n:",n," n1:",n1," n2:",n2,"<br>");
    document.write("this.n3:",this.n3," test.n4:",test.n4,"<br>");
    document.write(test.n3,"<br>");
    document.write(this.n4,"<br>");
  }
}

function print()
{
    document.write("<br>--function print--<br>");
    document.write("n1:",n1," test.n4:",test.n4,"<br>");
    document.write("this.n3:",this.n3,"<br>");
    document.write("n2:",n2,"<br>");
}
</script>
</head>

<body>
<h1>Javascript の Class の領域</h1>

<script type="text/javascript">
  var cls = new test(10);
  cls.type();
  print();
</script>

変数にはグローバル変数とローカル変数があります。
グローバル変数はどこからでも参照することができますが、ローカル変数は宣言された関数内でのみ参照できます。
関数内で var を付けて宣言された変数は、ローカル変数となります。
var を付けない場合はグローバル変数になります。

n は Constructor に渡されたパラメータを参照するための名前(仮引数)です。
this は現在(test が呼ばれたとき)のインスタンスで、this. で修飾された領域は、そのクラスに付属します。
同様にクラス名(test.)で修飾された領域は、そのクラス(test)に付属します。
function test(n)
{
  n1 = n+1;
  var n2 = n+2;
  this.n3 = n+3;
  test.n4 = n+4; 

type() は変数を印字する内部関数です。
[n1] と [var n2] はグローバル変数とローカル変数ですが、同じように参照出来ました。
今回の場合、n3 も n4 も test に付属すると思うのですが、修飾子が異なると参照できませんでした。 (^_^;)
  this.type = function()
  {
    document.write("n:",n," n1:",n1," n2:",n2,"<br>");
    document.write("this.n3:",this.n3," test.n4:",test.n4,"<br>");
    document.write(test.n3,"<br>");
    document.write(this.n4,"<br>");
  }
}

print() は test Class とは独立した関数です。
ここから n1 と test.n4 を参照することが出来ました。
this.n3 は undefined になり、n2(ver n2 で宣言)はエラーになりました。
[F12]キーでデバッグ機能を起動すると次のメッセージが表示されました。
'n2' は定義されていません。
function print()
{
    document.write("<br>--function print--<br>");
    document.write("n1:",n1," test.n4:",test.n4,"<br>");
    document.write("this.n3:",this.n3,"<br>");
    document.write("n2:",n2,"<br>");
}
</script>

new test(10); で Class を生成して cls.type(); で変数を印字します。
次に test Class とは独立した print() 関数を呼び出します。

cls.type() では test.n3, this.n4 が参照出来ませんでした。
(正しくは this.n3, test.n4 です。)
print() では this.n3, n2 は参照出来ません。
n3 は this で宣言された変数で、n2 は var で宣言されたローカル変数です。
<script type="text/javascript">
  var cls = new test(10);
  cls.type();
  print();
</script><br>

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