在初始化时引用其自身属性的对象 [英] Object referencing its own property on initialization

查看:136
本文介绍了在初始化时引用其自身属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

对象文字/初始值设定项中的自引用

可以这样做吗? (显然不在此语法中)

var a = {
    b : 10,
    c : this.b * 2 // returns 'undefined'
};

我也尝试了

var a = {
    b : 10,
    c : a.b * 2 // throws error 'a is undefined'
};

var a = {
    b : 10,
    c : b * 2 // throws error 'b is undefined'
};

我觉得这些值是未定义的,我还没有完成定义。然而,在我看来,似乎会有一个解决方案来构建这样的对象,并且 c 是以 b 为条件的>

It makes sense to me that these values are undefined, I have not finished defining them. However it seems to me like there would be a solution to structuring a object like that and having c be conditional on b

推荐答案

或者,您可以使用自启动功能为您提供与您所寻找的类似的效果:

Alternatively, you can use a self starting function to give you a similar affect to what you are looking for:

var a = (function() {
    var b = 10;
    return {
        b:b,
        c:b*2
    }
})();

console.log(a.c);

这篇关于在初始化时引用其自身属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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