这是我从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
?