0

I am currently going through 'Javascript: The good parts' by Douglas Crockford, and I'm trying to understand what a closure is exactly. It describes it as follows :

"The function object created by a function literal contains a link to that outer
context. This is called closure. "

and provides this example :

var add = function (a, b) {
return a + b;
};

However all I see here is a function literal and not a closure, if I am understanding correctly. So in its simplest form, how would a closure look like?

LogixMaster
  • 586
  • 2
  • 11
  • 36
  • 1
    Take a look of http://stackoverflow.com/questions/12930272/javascript-closures-vs-anonymous-functions i think this will help you – Ryokel May 30 '14 at 10:11
  • 1
    Technically, that literal would *still* create a closure around any surrounding variables. However, it just isn't a very useful one. Closures are useful when you the function literal needs to persist longer the outside scope would. The simpliest *useful* closure I can think of is `var add = function (to) { return function (val) { alert(val + to); }; };`. Use as `var adder = add(4); adder(5); adder(6);` etc. The returned function literal creates a closure over the `to` variable. – Matt May 30 '14 at 10:19
  • Thanks for both useful comment! These helped me understand better what closures are! cheers – LogixMaster May 30 '14 at 11:36

0 Answers0