最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Current object property as value in same object different property - Stack Overflow

programmeradmin3浏览0评论

Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.

So, when declaring a new object, I'm looking to calculate the giga value:

var myObject = {
    super : 1,
    mega : 5,
    uber : 100,
    giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};

But this doesn't work, so, any ways of doing this while declaring, or not possible?

Hope I've made myself clear and thanks in advance!

Sorry for such a random title, but have no idea how to explain it better. And therefore, no idea if this is a duplicate question or not.

So, when declaring a new object, I'm looking to calculate the giga value:

var myObject = {
    super : 1,
    mega : 5,
    uber : 100,
    giga : this.super + this.mega + this.uber // super + mega + uber doesn't cut it either..
};

But this doesn't work, so, any ways of doing this while declaring, or not possible?

Hope I've made myself clear and thanks in advance!

Share Improve this question edited Nov 7, 2011 at 12:58 tomsseisums asked Nov 7, 2011 at 12:50 tomsseisumstomsseisums 13.4k20 gold badges88 silver badges148 bronze badges 1
  • 1 possible duplicate of Self-references in object literal declarations – Felix Kling Commented Nov 7, 2011 at 13:07
Add a ment  | 

3 Answers 3

Reset to default 6

In Javascript 1.5 you can use the get keyword to define a getter

var obj = {
    super : 1,
    mega : 5,
    uber : 100,
    get giga() {
        return this.super + this.mega + this.uber;
    }
};

alert(obj.giga) // 106

more on this http://robertnyman./2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

I assume you have a really good reason for the need to do this inline, otherwise such trickery is not really a good idea.

Here is what I came up with:

var myObject = (function(){
    this.giga = this.super + this.mega + this.uber;
    return this;
}).call({
    super : 1,
    mega : 5,
    uber : 100
});
var myObject = {
    super : 1,
    mega : 5,
    uber : 100
};
myObject.giga = myObject.super + myObject.mega + myObject.uber;
发布评论

评论列表(0)

  1. 暂无评论