One common issue I encounter is the need to wrap a function on an object for various reasons. Is there a sophisticated method to maintain the original function's length
property on the wrapper function?
For instance:
var x = {
a: function(arg1, arg2) { /* do something */ }
};
function wrap(obj) {
var original = obj.a;
obj.a = function wrapper() {
console.log('a called');
original.apply(this, arguments);
};
}
x.a.length; // => 2
wrap(x);
x.a.length; // => 0
What I aim to achieve:
var x = {
a: function(arg1, arg2) { /* do something */ }
};
function wrap(obj) {
var original = obj.a;
obj.a = function wrapper() {
console.log('a called');
original.apply(this, arguments);
};
obj.a.length = original.length;
}
x.a.length; // => 2
wrap(x);
x.a.length; // => 2 (still actually 0)
However, this approach fails due to the non-writable nature of the length
property.
Currently, my only solutions involve either (1) creating the function dynamically as a string and using eval
/new Function
, or (2) maintaining a large array of proxy functions with different lengths and selecting the appropriate one. These options don't seem elegant to me, and it should be reasonable to create a function with any length
without explicitly specifying each argument within the function.
It appears that bind
can internally handle this scenario:
function a(b, c) { }
a.bind(null).length; // => 2
This generates a wrapper function with the original length! This functionality is precisely what I would like to replicate myself.
Are there any other methods to achieve this goal?