1

I am trying to create a function that can then return many functions based on an input. Here is an example of the problem I am facing.

var giveFunction = function(text) {
    return function(text) {
        console.log(text)
    }
}
var test = giveFunction('this is a test');
test()

Running test() at the end prints undefined instead of 'this is a test.' Is there any way around this problem?

1
  • invoke it as test("this is a test") Commented Mar 30, 2016 at 18:05

2 Answers 2

4

The inner function should not contain any parameter,

var giveFunction = function(text) {
    return function() {
        console.log(text)
    }
}

Let it create a closure. If it has a parameter then that would be read during execution and undefined would be printed as you are not calling that function with any arguments.

If you want your code to be working then you have to use bind for that,

var giveFunction = function(text) {
    return function(text) {
        console.log(text)
    }.bind(null, text)
}
var test = giveFunction('this is a test');
test();  //'this is a test'
Sign up to request clarification or add additional context in comments.

4 Comments

What is the significance of using bind vs closure in this case? Seems like using closure is the smarter choice here.
@Elliot I don't understand what you are asking. Closure and bind works in a different way.
I was wondering if there is any particular reason to go with the bind instead of using closure here, but perhaps that is a whole other stack question in itself. Thank you for the help understanding this!
@Elliot Glad to help! :)
1

Lets go one step further and ask why?

var outerFunction = function(outerParameter) {
   return innerFunction function(innerParameter) {
     // in here we have access to anything in this function and the outer function
     // all the way to out the the global scope
     // therefore, we dont need to pass innerParameter in again as a parameter! ( in your case we 'next')
   }
  /// now over here, outside of innerFunction, we do NOT have access to innerParameter!
}

So applying the above principles to your code we have:

var giveFunction = function(text) {
    return function() {
        console.log(text)
    }
}
var test = giveFunction('this is a test');
test()

which now works!

Finally, checkout the most upvoted post under the javascript tag: How do JavaScript closures work?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.