LoginSignup
0
1

More than 5 years have passed since last update.

javascriptパターン:5.7 オブジェクトの定数

Posted at

javascriptパターン 優れたアプリケーションのための作法
5.7 オブジェクトの定数 を試しました。

本を読んでいるだけだと、どんな動きをしているのかイメージが正しく持てなかったので自分なりにコメントをつけながら検証。


    var constant = (function () {
        var constants = {};
        var ownProp = Object.prototype.hasOwnProperty,
            allowd = {
                string: 1,
                number: 1,
                boolean: 1
            },
            prefix = (Math.random() + "_").slice(2);
        return {
            set: function (name, value) {
                if (this.isDefined(name)) {
                    return false;//存在していたら終り
                }
                if (!ownProp.call(allowd, typeof value)) {
                    return false;//すでに値がはいっていたら終り(上書き禁止)
                }
                constants[prefix + name] = value;//プロパティの追加
                return true;
            },
            isDefined: function (name) {
                return ownProp.call(constants, prefix + name) //存在のチェック
            },
            get: function (name) {
                if (this.isDefined(name)) {//存在していたらその値を表示
                    return constants[prefix + name]
                }
                return null
            },
            check: function () {//今まで登録したconstantsのプロパティを全部表示
                for (var prop in constants) {
                    console.log(prop + " = " + constants[prop] + ', ' + typeof constants[prop]);
                }
            }
        };

    }())

    console.log(constant.isDefined("maxwidth"));//maxwidthは定義されていますか?            false
    console.log(constant.set("maxwidth", 480));//maxwidthを定義します                      true
    console.log(constant.set("hello", 'こんにちわ'));//helloを定義します                    true
    console.log(constant.set("canYouEatCarrots", false));//canYouEatCarrotsを定義します    true
    console.log(constant.isDefined("maxwidth"));//maxwidthは定義されていますか?            true
    console.log(constant.set("maxwidth", 320));//maxwidthを再定義します。でもすでにあるので  false
    console.log(constant.get("maxwidth"));//再定義したmaxwidthの値はどうなったか?           480

    console.log(constant.check());//検証用に追加したメソッド:現在定義した全てを、型と共に出力。
                                  //30403848452875515_maxwidth = 480, number
                                  //30403848452875515_hello = こんにちわ, string
                                  //30403848452875515_canYouEatCarrots = false, boolean

定数を、javascriptで設定することが出来ました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1