【问题标题】:Named parameter in Javascript without overriding the existing valuesJavascript中的命名参数而不覆盖现有值
【发布时间】:2013-08-02 22:29:09
【问题描述】:

这是我从 Named parameters in javascript 得到的代码:

var parameterfy = (function () {
    var pattern = /function[^(]*\(([^)]*)\)/;

    return function (func) {
       // fails horribly for parameterless functions ;)
       var args = func.toString().match(pattern)[1].split(/,\s*/);

       return function () {
           var named_params = arguments[arguments.length - 1];
           if (typeof named_params === 'object') {
              var params = [].slice.call(arguments, 0, -1);
              if (params.length < args.length) {
                  for (var i = params.length, l = args.length; i < l; i++) {
                      params.push(named_params[args[i]]);
                  }
                  return func.apply(this, params);
              }
           }
           return func.apply(null, arguments);
       };
     };
}());

var myObject = {
    first: "",
    second: "",
    third: ""
};

var foo = parameterfy(function (a, b, c) {
        //console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
        myObject.first = a;
        myObject.second = b;
        myObject.third = c;
        console.log("first " + myObject.first + " second " + myObject.second + " third " + myObject.third);
});


foo(1, 2, 3); // gives 1, 2, 3
foo({a: 11, c: 13}); // gives 11, undefined, 13
foo({ a: 11, b:myObject.second, c: 13 });  // in order to avoid undefined, this is 

请注意,在foo 的第二个实例中,我得到了undefined,因为我没有通过b,所以我不得不使用第三个实例来解决我传递b 的当前值的问题。

无论如何,如果我不必传递一个值,例如,b 在这种情况下,它仍然会更新ac 的给定值,但是保留b 的值?

【问题讨论】:

  • 说真的……为什么?只需使用每个人都使用的标准模式,远离麻烦。
  • 您指的是哪种标准模式?我有大约 30 个变量需要定期初始化和更新。

标签: javascript named-parameters


【解决方案1】:

这是已成功使用多年的命名参数标准,您应该坚持下去:

function myFunction(options) {
    console.log(options.first);
    console.log(options.second);
    console.log(options.third);
}

myFunction({
    first: 1,
    second: 2,
    third: 3
});

【讨论】:

  • 我猜你是对的,好像我把事情复杂化了……谢谢。
【解决方案2】:

类似下面的方法可能会起作用:

var foo = parameterfy(function (a, b, c) {
    //console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
    if(typeof a != 'undefined'){myObject.first = a;}
    if(typeof b != 'undefined'){myObject.second = b;}
    if(typeof c != 'undefined'){myObject.third = c;}
    console.log("first " + myObject.first + " second " + myObject.second + " third " + myObject.third);
});

【讨论】:

  • 工作 :) 感谢 user506069!如果有人知道这个问题的任何更好的方法或更好的命名参数技术,请告诉我。
猜你喜欢
  • 2012-03-31
  • 2012-03-22
  • 1970-01-01
  • 2017-07-22
  • 2012-05-26
  • 2015-06-05
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
相关资源
最近更新 更多