1

I have a little class that extends the Date object in JavaScript. One method just returns the current Date in UTC.

Date.prototype.nowUTC = function(options) {

    var now = new Date();

    return new Date(now.getUTCFullYear(), 
                    now.getUTCMonth(), 
                    now.getUTCDate(), 
                    now.getUTCHours(), 
                    now.getUTCMinutes(), 
                    now.getUTCSeconds());
}

What I'd like to do is define the options parameter as an object that will contain hours, minutes, and seconds, which will be added to the time. For example,

Date.prototype.nowUTC = function(options) {

    var now = new Date();

    return new Date(now.getUTCFullYear(), 
                    now.getUTCMonth(), 
                    now.getUTCDate(), 
                    now.getUTCHours() + options.hours, 
                    now.getUTCMinutes() + options.minutes, 
                    now.getUTCSeconds()) + options.seconds;
}

Is there a way to pre-define these values, so I don't have to check if it's defined before adding it or set a default? (such as function(options = {'hours' : null, 'minutes' : null, 'seconds' : null) {}) Id prefer to handle the parmeter like - as one object - instead of passing separate params for each value.

Thank you!

4

2 回答 2

3

您可以制作一个小迭代器来检查对象属性:

Date.prototype.nowUTC = function(options) {

    // Object holding default values for this function
    var defaults = {
      "hours": <default>,
      "minutes": <default>,
      "seconds": <default>
    };

    // Iterate over the options and set defaults where the property isn't defined.
    for (var prop in defaults)  {
      options[prop] = options[prop] || defaults[prop];

      // Note: if options would contain some falsy values, you should check for undefined instead.
      // The above version is nicer and shorter, but would fail if, for example, 
      //    options.boolVal = false
      //    defaults.boolVal = true
      // the defaults would always overwrite the falsy input property.
      options[prop] = typeof options[prop] !== 'undefined' ? options[prop] : defaults[prop];
    }

    var now = new Date();
    // Rest of your function, using the options object....
};
于 2012-04-04T19:34:50.047 回答
1

Object.assign是将值分配给对象并使用输入扩展该对象的最简单方法。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

所以在你的情况下:

Date.prototype.nowUTC = function(options) {

    var defaults = {
        hours: 0,
        minutes: 0,
        seconds: 0,
    };
    var now = new Date();

    options = Object.assign(defaults, options);

    return new Date(now.getUTCFullYear(), 
                    now.getUTCMonth(), 
                    now.getUTCDate(), 
                    now.getUTCHours() + options.hours, 
                    now.getUTCMinutes() + options.minutes, 
                    now.getUTCSeconds()) + options.seconds;
}
于 2018-06-25T18:52:59.750 回答