はじめに
グローバル変数を沢山作ると結構ややしくなる
test.html
<script>
var now = new Date(),
current_full_year = now.getFullYear(),
current_month = now.getMonth(),
current_date = now.getDate(),
current_hours = now.getHours(),
current_minutes = now.getMinutes(),
current_seconds = now.getSeconds();
</script>
コンソールで確認してみる
console
//今の年は?
current_full_year
2019
//じゃ、今の分は?
durrent_minutes
Uncaught ReferenceError: current_minute is not defined
at <anonymous>:1:13
//なぬ!!変数名違ったっけ?タイプミスか?…あ、最初の文字はdじゃなくてcだ!
current_minutes
33
//よしよし!そんじゃ気分一新!グローバル変数をまとめて消しちゃおう!!
//…簡単にはできない…
//ならば全てのグローバル変数に格納されている値を一望してみよう
//…簡単にはできない…
//…
と、ちょっと扱いにくいことがある。
全てのグローバル変数を1つの変数に集約してみる
test2.html
<script>
var data = {
now : new Date(),
current_full_year : now.getFullYear(),
current_month : now.getMonth(),
current_date : now.getDate(),
current_hours : now.getHours(),
current_minutes : now.getMinutes(),
current_seconds : now.getSeconds()
};
</script>
コンソールで確認してみる
console
//今の年は時は?
data.current_full_year
2019
//じゃ、今の分は?※今度はスペルミスしたくない
data.
//全てのプロパティが予測変換できるので、入力も楽だし入力ミスもない
data.current_minutes
47
//よしよし。それじゃ全てのグローバル変数に格納されている値を一望してみよう
data
{now: Mon Aug 19 2019 10:47:48 GMT+0900 (日本標準時), current_full_year: 2019, current_month: 7, current_date: 19, current_hours: 10, …}
//試しに全部消してみっか!
data=undefined
undefined
//消えていることを確認
data
undefined
data.current_full_year
VM961:1 Uncaught TypeError: Cannot read property 'current_full_year' of undefined
at <anonymous>:1:6
少し書き方を変えるだけで頭すっきりしました(^^)