Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

In my program, I will only ever need one instance of this so I used a singleton Object. However, is there a better way to write this so I don't have to use so much wording when retrieving the key/values? example: instead of date.foo.month....maybe just date.month?

var date = function() {
    var dateObj = new Date();
    var foo = {
        month: dateObj.getMonth() + 1,
        date: dateObj.getDate(),
        year: dateObj.getFullYear(),
    }

    return {
        foo: foo,
    }
}();

alert(date.foo.month);​
share

migrated from stackoverflow.com Oct 6 '12 at 1:06

This question came from our site for professional and enthusiast programmers.

locked by Jamal Aug 10 at 0:04

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

2 Answers 2

up vote 4 down vote accepted

What about:

var date = (function() {
  var dateObj = new Date();
  return {
    month: dateObj.getMonth() + 1,
    date: dateObj.getDate(),
    year: dateObj.getFullYear(),
  }
}());
share
    
Thanks. Does this mean though the keys get refreshed everytime I call them such as date.month? –  d hee Oct 5 '12 at 3:27
    
No, they are set in the object literal. The value of a Date object doesn't change over time, it's set on creation and only modified by calling the set* methods with different values. –  RobG Oct 5 '12 at 3:29

If getters and setters are available in the target audience (e.g. company intranet using Gecko based browsers):

var date = (function() {
  var now = new Date();
  return {
    get date() {return now.getDate();},
    set date(value) {now.setDate(value);},

    get month() {return now.getMonth() + 1;},
    set month(value) {now.setMonth(--value);},

    get year() {return now.getFullYear();},
    set year(value) {now.setFullYear(value);},

    get ISOString() {
            function z(n) {return (n<10?'0':'') + n}
            return now.getFullYear() + '-' + 
                   z(now.getMonth() + 1) + '-' +
                   z(now.getDate());
    } 
  }
}());

// On 5-Oct-2012
date.date;      // returns 5
date.month = 3; // sets month to March
date.month;     // returns 3
date.ISOString; // returns 2012-03-05
share

Not the answer you're looking for? Browse other questions tagged or ask your own question.