指定要传递的参数

Specifying which parameter to pass

考虑一下我在 C# 中有如下所示的方法。

void DoSomething(bool arg1 = false, bool notify = false)
{ /* DO SOMETHING */ }

我可以像这样指定传递给方法的参数:

DoSomething(notify: true);

而不是

DoSomething(false, true);

Javascript可以吗?

您可以通过传递对象来实现类似的目的:

function DoSomething(param) {
  var arg1 = param.arg1 !== undefined ? param.arg1 : false,
      notify = param.notify !== undefined ? param.notify : false;

  console.log('arg1 = ' + arg1 + ', notify = ' + notify);
}

DoSomething({ notify: true });

这是不可能的,但您可以通过传递对象并添加一些自定义代码来解决这个问题

/**
 * This is how to document the shape of the parameter object
 * @param {boolean} [args.arg1 = false] Blah blah blah
 * @param {boolean} [args.notify = false] Blah blah blah
 */
function doSomething(args)  {
   var defaults = {
      arg1: false,
      notify: false
   };
   args = Object.assign(defaults, args);
   console.log(args)
}

doSomething({notify: true}); // {arg1: false, notify: true}

你可以概括这个

createFuncWithDefaultArgs(defaultArgs, func) {
    return function(obj) {
        func.apply(this, Object.assign(obj, defaultArgs);
    }
}

var doSomething = createFuncWithDefaultArgs(
    {arg1: false, notify: false}, 
    function (args) {
         // args has been defaulted already

    }
); 

请注意 Object.assign 在 IE 中不支持,you may need a polyfill

将对象作为参数传递:

function DoSomething(obj){

 if (obj.hasOwnProperty('arg1')){

  //arg1 isset
 }

 if (obj.hasOwnProperty('notify')){

  //notify isset
 }

}

用法:

DoSomething({
 notify:false
});

ES2015 的通用约定是传递 an object as a single argument,为其属性分配默认值,然后在函数内部使用解构:

const DoSomething = ({ arg1 = false, notify = false } = {}) => {
  /* DO SOMETHING */
};

DoSomething({ notify: true }); // In the function: arg1=false, notify= true

您可以在没有任何参数的情况下调用此函数,即 DoSomething(),但这需要对象的默认值(参数列表末尾的 = {})。