简体   繁体   English

定义 object 默认为 JavaScript function 参数

[英]Define object defaults for JavaScript function parameters

I have a little class that extends the Date object in JavaScript. One method just returns the current Date in UTC.我有一个小的 class,它在 JavaScript 中扩展了日期 object。一种方法只返回 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.我想要做的是将选项参数定义为 object,它将包含小时、分钟和秒,这些将被添加到时间中。 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. (例如function(options = {'hours': null, 'minutes': null, 'seconds': null) {} )我更喜欢像处理参数一样 - 作为一个 object - 而不是为每个值传递单独的参数。

Thank you!谢谢!

You can make a little iterator to check the object properties:您可以制作一个小迭代器来检查 object 属性:

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

Object.assign is the easiest way to assign values to an objects and extend that object with input. Object.assign是为对象赋值并使用输入扩展 object 的最简单方法。

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

So in your case:所以在你的情况下:

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

Similar to Object.assign , you can use spread syntax :类似于Object.assign ,你可以使用扩展语法

 const func = (options = {}) => { options = { foo: 1, bar: 2, baz: 3, ...options }; console.log(options); }; func({baz: "c", foo: "a"});

Or destructuring :解构

 const func = ({foo = 1, bar = 2, baz = 3} = {}) => { console.log(foo, bar, baz); }; func({baz: "c", foo: "a"});

Although perhaps not quite an exact duplicate, Set a default parameter value for a JavaScript function is a great canonical to browse through.虽然可能不完全相同, 但为 JavaScript function 设置默认参数值是一个很好的浏览规范。

Regarding Date.prototype.nowUTC , it's considered poor practice to modify library prototypes.关于Date.prototype.nowUTC ,修改库原型被认为是不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM