I’m new to javascript, and came across the ‘apply’ method.
As an exercise, I’ve tried to create a wrapper function for all functions, like the following snippet. 1. Why is this not working as expected, and 2. how can I create a wrapper function for all functions?
function funcWrapper(func){
return func.apply(this, arguments);
};
function sum(num1, num2){
return num1 + num2;
}
funcWrapper(sum, 2, 3);
// expected 5, but returns
// function sum(num1, num2){
// return num1 + num2;
// }2
It’s because the arguments object in funcWrapper is
[function sum(num1, num2){ return num1 + num2; }, 2, 3], the first argument is the function that you pass. Theargumentsobject is all of the arguments that you pass to the function.The solution is to exclude the first argument which is the object. Usually in javascript, people use the slice method of the arrays. Well you might ask yourself that
argumentsis an object, and doesn’t have that method. But we can do the following workaround:In the funcWrapper. Which again you make it shorter by converting the first line to this:
You can also wrap that into a function like this:
And use it like this:
Note that in ES6(Not implemented in browsers) this problem is solved by using rest parameters:
One more thing, that when you are trying to wrap constructors, make sure you also inherit the prototype too, or you fall into the same trap as this question: jQuery logger plugin