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

前端 未结 5 1852
谎友^
谎友^ 2021-01-19 15:26

Say I have an object such as this:

var time = {
    \'second\': 1000,
    \'minute\': 1000 * 60,
    \'hour\'  : 1000 * 60 * 60,
    \'day\'   : 1000 * 60 *          


        
相关标签:
5条回答
  • 2021-01-19 15:47

    You can't do this as the object does not exist yet while it's parsed.

    The only way to avoid this is creating an object and then adding the keys one by one - so you already have an object which has the properties you want to re-use.

    0 讨论(0)
  • 2021-01-19 15:48

    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;
    ...
    
    0 讨论(0)
  • 2021-01-19 15:48

    You can use the getters syntax supported by most modern browser :

    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;
         }
    };
    
    0 讨论(0)
  • 2021-01-19 15:58

    Change the object to a constructor function and you 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();
    
    0 讨论(0)
  • 2021-01-19 16:00
    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}}()
    
    0 讨论(0)
提交回复
热议问题