或者,换句话说,如何使这项工作:
function foo(){}
//do something that modifies foo as if it was defined with "function foo(a,b,c){};"
console.log(foo.length);
//output: 3
或者,换句话说,如何使这项工作:
function foo(){}
//do something that modifies foo as if it was defined with "function foo(a,b,c){};"
console.log(foo.length);
//output: 3
这是可能的,但可能不是很好:
function lengthDecorator(fun) {
function update(len) {
var args = []; // array of parameter names
for (var i = 0; i < len; ++i) {
args.push('a' + i);
}
var result = new Function('fun',
'return function(' + args.join(',') + ') {' +
'var args = Array.prototype.slice.call(arguments);' +
'return fun.apply(this, args);' + // call supplied function
'}'
); // create a function that will return a function
result = result(fun); // make the fun param known to the inner function
result.update = update;
return result;
}
return update(fun.length);
}
示例用法:
var foo = lengthDecorator(function(a,b) {
return a+b;
});
print('foo.length: ' + foo.length);
print('foo(2, 3): ' + foo(2, 3));
print('');
foo = foo.update(42);
print('foo.length: ' + foo.length);
print('foo(2, 3): ' + foo(2, 3));
输出:
foo.length: 2 富(2、3):5 foo.length:42 富(2、3):5
(现场演示:Ideone.com、jsFiddle)
lengthDecorator
用一个函数包装提供的函数,该函数采用与提供的函数相同数量的参数。可以使用 更改参数计数update
。
比照
new Function(...)
:动态创建新功能。fun.apply(...)
:“使用给定的 this 值和作为数组提供的参数调用函数。”function foo() {}
alert(foo.length); // 0
foo = function (a, b, c) {}
alert(foo.length); // 3
我不确定您实际上要做什么,但是您可以将旧的存储foo
在 var 中,然后重新定义foo
.
function foo() {...}
var oldfoo = foo;
foo = function (a, b, c) {
oldfoo();
}
但有什么意义呢?
函数对象的length
属性是不可写和不可配置的,所以没有办法改变它的值。
您可以定义一个在内部调用原始函数的新函数...