0

I can't figure out what's wrong with the following code and why would it work when I do it using the second way. Can anyone please help me understand this?

I have this following Javascript code:

var clsFunc = function(prefix) {
  var id = 0;
  return function() {
    id = id + 1;
    console.log(prefix + id);
  }
}

First way (did not work):

If I try to call this function like this nothing happens

clsFunc('div') 

Second way (worked)

var getId = {'div': clsFunc('div')}

getId.div()

Result:

div1
undefined
getId.div()

Result:

div2
JJJ
  • 32,902
  • 20
  • 89
  • 102
Shibasis Sengupta
  • 629
  • 1
  • 6
  • 21

1 Answers1

2

The clsFunc function creates a function and returns it. So just doing

clsFunc('div');

...is pointless, because it creates a function and then just throws it away, because you didn't store it anywhere.

The second way stores the function that was created in an object property. That function has a reference to the context that created it (the call to clsFunc), even though that call has returned, which contains the id variable. When you call the function (getId.div()), it adds 1 to id and then outputs the prefix ("div") followed by the new value if id (1, then 2, then, 3, etc.).

You don't need an object for your second way, you could just use a variable:

var clsFunc = function(prefix) {
  var id = 0;
  return function() {
    id = id + 1;
    console.log(prefix + id);
  }
};

var f = clsFunc('div');
f(); // "div1"
f(); // "div2"

(The undefineds you're seeing are just because you're running this in a JavaScript console that shows you the result of calling the function; since the function doesn't return anything, the result of calling it is undefined.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875