Harold - 6 months ago 27

Javascript Question

If I have:

`var calc = function(){`

return {

adder: function(x,y){return x+y;}

}

};

calc();

calc.adder(4,5);

calc.adder is undefined. However, if I immediately invoke calc as

`var calc = function(){`

return {

adder: function(x,y){return x+y;}

}

}();

calc.adder(4,5);

things work as expected. Why does the first example fail?

Answer

`calc()`

is a function that returns an object that contains a function called `adder()`

. So this will work.

```
var calc = function(){
return {
adder: function(x,y){return x+y;}
}
};
var cal = calc();
cal.adder(4,5);
```

The line of code

```
calc();
```

Stores the returned object in no variable, so you can't use the object.

The second example you posted is essentially the same thing. The calc variable is no longer a function, it is the object that the un-named function returns when you execute it with the `()`

;