The length property of functions tells how long the ‘expected’ argument list is:
console.log((function () {}).length); /* 0 */
console.log((function (a) {}).length); /* 1 */
console.log((function (a, b) {}).length); /* 2 etc. */
However, it is a readonly method:
f = function (a) {};
alert(f.length); // 1
f.length = 3;
alert(f.length); // 1
Is there a way to programmatically set that length? The closest I’ve come so far is to use the Function constructor:
f = new Function("a,b,c", "/* function body here */");
f.length; // 3
However, using Function is essentially the same as eval and we all know how bad that is. What other options do I have here?
For now, here’s the best solution I could think of.
Example usage:
Personally, I always cringe whenever I use copy and paste when programming, so I’d be very happy to hear of any better options.
Update
I thought of a method which could work for any arbitrary size, unlike the example above which is limited by how many times you want to copy-and-paste. Essentially, it dynamically creates a function (using
new Function) which will return a function of the right size which then just proxies through to whatever function you pass to it. Yeah that does hurt your head. Anyway, I thought I’d benchmark it against the above…http://jsperf.com/functions-with-custom-length (you can see the ‘evil’ code there too).
The evil method is many hundreds of times slower than the hacky copypasta method, so there you go.