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

Say I have an object like 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 that it refers to 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 cannot reference everyone using time.foo because the variable is not yet initialized. I could just add every new command, for example time['hour'] = time.minute * 60; but I would rather do it with a single command.

+4
source share
5 answers
 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, a miniature version:

 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}}() 
+5
source

you cannot reference properties from yourself, if you declare it like this, since the properties do not exist yet, you can try a different approach

 var time = {}; time.second = 1000; time.minute = time.second * 60; ... 
+6
source

You cannot do this because the object does not yet exist while it is being parsed.

The only way to avoid this is to create an object and then add the keys one by one - so that you already have an object that has properties that you want to reuse.

+3
source

Change the object to the constructor function, and can do this:

 function Time() { this.second = 1000; this.minute = this.second * 60; this.hour = this.minute * 60; this.day = this.hour * 24; this.week = this.day * 7; } // Use var time = new Time(); 
+3
source

You can use getters syntax supported by most modern browsers:

 var time = { 'second': 1000, get minute () { return this.second * 60; }, get hour (){ return this.minute * 60; }, get day (){ return this.hour * 24; }, get week (){ return this.day * 7; } }; 
+1
source

Source: https://habr.com/ru/post/1433899/


All Articles