javascript对象文字使用它自己的字段 [英] javascript object literals using it's own fields

查看:95
本文介绍了javascript对象文字使用它自己的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个包含特定组件的整个配置的对象。我也会这样说谎:

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?

编辑:
对不起,我是手工编写的,这是语法错误的来源。现在这是正确的。我得到的错误是未捕获TypeError:无法读取未定义的属性'fieldKeys'。我想这样做是不可能的 - 那么最好的选择是什么呢?

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?

推荐答案

你的问题是对象是构造的从文字之前,它被分配给 ObjectConfig 变量。因此,在文字内访问 ObjectConfig.fieldKeys 将导致错误。

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

另一个(更短的)方法是key对象的额外变量,在构造之前分配模板对象:

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

要在全局范围内解决额外变量,可以使用 IEFE 。更可读的解决方案可能如下所示:

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

这篇关于javascript对象文字使用它自己的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆