2012-04-04 56 views
1

我有一个用JavaScript扩展Date对象的小类。一种方法只是以UTC形式返回当前日期。定义JavaScript函数参数的对象默认值

Date.prototype.nowUTC = function(options) { 

    var now = new Date(); 

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

我希望做的是定义选项参数作为对象,将包含小时,分钟和秒,这将被添加到的时间。例如,

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; 
} 

有没有办法预先定义这些值,所以我没有检查,如果它的加入,或设置一个默认的前界定? (例如function(options = {'hours' : null, 'minutes' : null, 'seconds' : null) {})Id更喜欢像 - 作为一个对象一样处理参数 - 而不是为每个值传递单独的参数。

谢谢!

回答

2

你可以做一点迭代器来检查对象属性:

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.... 
};