Fieds_labo1
js-関数と変数
最終更新:
fieds_labo1
-
view
javascript 関数と変数
変数のスコープの基本は
- 変数は基本グローバル変数。
- 関数内で var で変数宣言をしたものだけが関数内のローカル変数。例:var a;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>無題ドキュメント</title>
<script language="JavaScript" type="text/javascript">
<!--
total = 0; // global
function abc() {
var subtotal=0;
subtotal++;
document.write('<br>abc.subtotal = '+subtotal+'<br>');
def();
document.write('<br>abc.def.subtotal = '+subtotal+'<br>');
total++;
}
function def(){
subtotal++;
document.write('<br>def.subtotal = '+subtotal+'<br>');
total++;
}
-->
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
document.write('<br>total = '+total+'<br>');
abc();
document.write('<br>total = '+total+'<br>');
def();
document.write('<br>total = '+total+'<br>');
-->
</script>
</body>
</html>
- 実行すると 関数abcから関数defをコールし、defの中でsubtotal未定義エラーになる。
- 関数内で定義したローカル変数は、その関数から呼ばれる子関数では有効にならない?
- 他に良い書き方があるかもだけど、こういう書き方では参照できませんでした@@;