Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a key from the same object when creating it?

Say I have an object such as this:

var time = {
    'second': 1000,
    'minute': 1000 * 60,
    'hour'  : 1000 * 60 * 60,
    'day'   : 1000 * 60 * 60 * 24,
    'week'  : 1000 * 60 * 60 * 24 * 7
};

How would I shorten it so it would reference the other keys?

I mean something like this:

var time = {
    'second': 1000,
    'minute': this.second * 60,
    'hour'  : this.minute * 60,
    'day'   : this.hour   * 24,
    'week'  : this.day    * 7
}

I can't reference each using time.foo because the variable isn't initialized yet. I could simply add each on a new command, such as time['hour'] = time.minute * 60;, but I'd rather do it in one command.

like image 695
Tgwizman Avatar asked Dec 02 '22 21:12

Tgwizman


2 Answers

you can't reference properties from itself if you are declaring it like that as the properties dont yet exist, you might want to try a different approach

var time = {};
time.second = 1000;
time.minute = time.second * 60;
...
like image 77
rroche Avatar answered Dec 10 '22 13:12

rroche


var time = (function(){
    var second = 1000,
        minute = second * 60,
        hour = minute * 60,
        day = hour * 24,
        week = day * 7;
    return {
        'second': second,
        'minute': minute,
        'hour'  : hour,
        'day'   : day,
        'week'  : week
    };
})();

UPD

Even shorter:

var time = (function(){
    var w, d, h, m, s;
    w = (d = (h = (m = (s = 1000) * 60) * 60) * 24) * 7;
    return {
        second: s,
        minute: m,
        hour  : h,
        day   : d,
        week  : w
    };
})();

And finally the minified version of this:

var time=function(){var a,b,c,d,e;a=(b=(c=(d=(e=1e3)*60)*60)*24)*7;return{second:e,minute:d,hour:c,day:b,week:a}}()
like image 23
dyurkavets Avatar answered Dec 10 '22 11:12

dyurkavets