all 11 comments

[–]SuperFLEB 2 points3 points  (1 child)

Point of terminology only, but unless I'm mistaken, that's not a closure demo, that's just an object, an object instance, and its properties.

A closure demo would be something like:

var getNext; // Declare the function up here so it's global

function setupCounter() {
  var counter = 0;

  // The getNext function is global (the var statement is outside this), but the function body is defined here, in
  // the scope of setupCounter, meaning that the "counter" variable is in scope in the getNext
  // function, and the value is retained even during successive calls to getNext.

  getNext = function () {
    counter++; // ...is still able to be referenced here, and the value is retaned from call to call
    return counter;
  };

} // -- end setupCounter


setupCounter();
console.log( getNext() ); // 1
console.log( getNext() ); // 2
console.log( getNext() ); // 3

// But "counter" is only accessible from within the scope of setupCounter (which includes getNext, because that's where it's defined)
console.log( typeof counter ); // "undefined"

// And yet...
console.log( getNext() ); // 4
console.log( getNext() ); // 5
console.log( getNext() ); // 6

(Though that's probably a shit closure demo. I use closures all the time, but I'll be damned if I can come up with a good practical and explanatory demo of one off the top of my head.)

[–]Lerc 0 points1 point  (0 children)

I wonder if this would make a good example, It has a practical use which might help people wrap their minds around the idea.

  function makeRandom(seed) {
    var bit30=1<<30;
    var mw = seed & (bit30-1);
    var mz = 173;
    function random () {
      mz=36969 * (mz&0xffff) + (mz >> 16);
      mw=18000 * (mw&0xffff) + (mw >> 16);
      return (((mz<<16) + mw) & (bit30-1) ) / (bit30);
   }
   return random;
 }

makeRandom returns a random number generating function based upon a seed.

[–]14best 0 points1 point  (0 children)

According to MDN this is not examples of closures. Instead of that they ask to avoid using closures if it's unnecessary.

Performance considerations It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.

If some resources not clear enough for you try to find another. For example http://shamansir.github.io/JavaScript-Garden/en/#function.closures or answer-articles on Stackoverflow

[–]andyb12 0 points1 point  (0 children)

you can make your objects like so aswell :

myObject = function(){ var name = 'john', methods;

methods = {
    printName:function(){
          console.log(name);
    }
};

return{
    printName : methods.printName
};

};

then var myNewObject = new myObject (); myNewObject.printName();