2012-04-04 70 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.... 
};