Hi I'm trying to run the following function:
function add (a, b) {
return a + b;
}
var make_lazy = function (add, a, b) {
return function () {
add(a,b);
}
}
Basically what I'm trying to do is to pass another function as an argument and its parameters to the make_lazy function - and then run the function that was passed in as the argument along with the other two parameters. I get undefined is not function as an error when I try to run the code.
4 Answers 4
You forgot the return statement in the anonymous function that you're returning from make_lazy:
var make_lazy = function (add, a, b) {
return function () {
return add(a,b) // <----- here
}
}
Comments
I think you are trying for something like this.
function add (a, b) {
return a + b;
}
var make_lazy = function (a, b) {
return function () {
return add(a,b);
}
}
Then you can call var lazy = make_lazy(3,5); and later call lazy() to get 8
2 Comments
add if it's the only function you're ever going to pass.Wrap you lazy function body inside a self calling function and return.
function add (a, b) {
return a + b;
}
var make_lazy = function (add, a, b) {
return (function () {
add(a,b);
})();
}
1 Comment
Here's my point of view.
When you assign a function to make_lazy variable, after that you should make an invocation make_lazy() with the same params as they were in the definition of that function:
make_lazy(function expression, a, b);
This portion:
function (add, a, b)
just makes add a local variable, this is not the same as add(a,b) which is defined above.
To make the code work, try to invoke make_lazy as
make_lazy(add, 3, 4)