指定要传递的参数

时间:2016-07-27 15:47:01

标签: javascript parameter-passing default-parameters

请考虑我在C#中使用如下方法。

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

我可以指定我传递给方法的参数如下:

DoSomething(notify: true);

而不是

DoSomething(false, true);

可以在Javascript中使用吗?

4 个答案:

答案 0 :(得分:2)

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(),但是这需要对象的默认值(参数列表末尾的= {})。

答案 1 :(得分:1)

你可以通过传递一个对象来实现类似的东西:

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

答案 2 :(得分:1)

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

/**
 * 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

    }
); 

请注意,IE you may need a polyfill

不支持Object.assign

答案 3 :(得分:0)

将对象作为参数传递:

function DoSomething(obj){

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

  //arg1 isset
 }

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

  //notify isset
 }

}

用法:

DoSomething({
 notify:false
});
相关问题