javascript object literals using it's own fields

谁说我不能喝 提交于 2019-12-02 12:13:15

问题


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 : {
        name: "Obj. name",
        state: "Obj. state",
        color: "Obj. color"
    },
    templates : {
        basicTemplate :  [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.state ],
        altTemplate : [ ObjectConfig.fieldKeys.name, ObjectConfig.fieldKeys.color ]
    }
}

But this in the right way to do it - it doesn't work. How can I achieve my goal?

EDIT: Sorry, I was writing it by hand in a hurry, that's where the syntax errors came from. Now it's correct. The error I get is Uncaught TypeError: Cannot read property 'fieldKeys' of undefined. I guess that doing it this way is impossible - what is the best alternative then?


回答1:


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 ]
        }
    };
})();


来源:https://stackoverflow.com/questions/14601624/javascript-object-literals-using-its-own-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!