Help us understand the problem. What is going on with this article?

グローバル変数を扱いやすくする工夫

More than 1 year has passed since last update.

はじめに

グローバル変数を沢山作ると結構ややしくなる

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

少し書き方を変えるだけで頭すっきりしました(^^)

sozaiya
よろしくお願いします ^^) _旦~~
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした