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?

Elliot
  • 1,893
  • 4
  • 17
  • 35

2 Answers2

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'
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
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?

Community
  • 1
  • 1
omarjmh
  • 13,632
  • 6
  • 34
  • 42