1

或者,换句话说,如何使这项工作:

function foo(){}
//do something that modifies foo as if it was defined with "function foo(a,b,c){};"
console.log(foo.length); 
//output: 3
4

4 回答 4

2

这是可能的,但可能不是很好:

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.comjsFiddle

lengthDecorator用一个函数包装提供的函数,该函数采用与提供的函数相同数量的参数。可以使用 更改参数计数update

比照

于 2012-06-12T01:12:05.800 回答
1
function foo() {}
alert(foo.length); // 0

foo = function (a, b, c) {}
alert(foo.length); // 3
于 2012-06-12T00:08:13.200 回答
0

我不确定您实际上要做什么,但是您可以将旧的存储foo在 var 中,然后重新定义foo.

function foo() {...}

var oldfoo = foo;
foo = function (a, b, c) {
    oldfoo();
}

但有什么意义呢?

于 2012-06-11T23:54:46.423 回答
-1

函数对象的length属性是不可写和不可配置的,所以没有办法改变它的值。

您可以定义一个在内部调用原始函数的新函数...

于 2012-06-12T00:03:28.593 回答