2

这是我从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在这种情况下的值,它是否仍然更新给定的值a并且c保留的值b

4

2 回答 2

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);
});
于 2013-08-01T20:11:43.473 回答
1

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

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

myFunction({
    first: 1,
    second: 2,
    third: 3
});
于 2013-08-01T20:51:37.463 回答