javascript object literals using it's own fields

后端 未结 1 1454
南旧
南旧 2021-01-24 15:31

I would like to create ONE object containing the whole config for certain component. I would liek it too be like this:

var ObjectConfig = {
    fieldKeys : {
            


        
1条回答
  •  温柔的废话
    2021-01-24 16:23

    Your problem is that the object is constructed from the literal before it is assigned to the ObjectConfig variable. Therefore, accessing ObjectConfig.fieldKeys inside the literal will lead to the error.

    The best solution is to construct first one object only, and then add further properties sequentially:

    var ObjectConfig = {
        fieldKeys: {
            name: "Obj. name",
            state: "Obj. state",
            color: "Obj. color"
        }
    };
    ObjectConfig.templates = {
        basicTemplate:  [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.state ],
        altTemplate: [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.color ]
    };
    

    Another (shorter) method would an extra variable for the keys object, which is assigned before the construction of the templates object:

    var keys, ObjectConfig = {
        fieldKeys: keys = {
            name: "Obj. name",
            state: "Obj. state",
            color: "Obj. color"
        },
        templates: {
            basicTemplate: [ keys.name, keys.state ],
            altTemplate: [ keys.name, keys.color ]
        }
    };
    

    To work around the extra variable in global scope, you might use an IEFE. A more readable solution might look like this then:

    var ObjectConfig = (function() {
        var keys = {
            name: "Obj. name",
            state: "Obj. state",
            color: "Obj. color"
        };
        return {
            fieldKeys: keys,
            templates: {
                basicTemplate: [ keys.name, keys.state ],
                altTemplate: [ keys.name, keys.color ]
            }
        };
    })();
    

    0 讨论(0)
提交回复
热议问题