Alex Rivera | Logout

Javascript Closure and Data Visibility

Asked 2009-06-03T21:25:23.807
12

I am trying to wrap my head around the idea of classes, data visibility and closures (specifically in Javascript) and I am On the jQuery docs page for types, it mentions that closures are used to hide data:

The pattern allows you to create objects with methods that operate on data that isn't visible to the outside—the very basis of object-oriented programming.

The example:

function create() {
  var counter = 0;
  return {
    increment: function() {
      counter++;
    },
    print: function() {
      console.log(counter);
    }
  }
}
var c = create();
c.increment();
c.print(); // 1

By declaring the variable counter with the keyword var, it is already locally scoped inside the function/class definition. As far as I know and can tell, it isn't accessible from the outside to begin with. Am I missing something from a data visibility perspective.

Second, is there an advantage to writing the class like above versus like below:

function create() {
  var counter = 0;
  this.increment = function() {
      counter++;
  }
  this.print = function() {
      console.log(counter);
  }
  return this;
}
var c = create();
c.increment();
c.print(); // 1

As I understand it, these are more or less semantically the same thing - the first is just more "jQuery style". I am just wondering if there is an advantage or other nuance I don't fully appreciate from the first example. If I am correct, both examples create closures in that they are accessing data declared outside their own scope.

http://docs.jquery.com/Types#Closures

Edit
Report

3 Answers

4

By declaring the variable counter with the keyword var, it is already locally scoped inside the function/class definition. As far as I know and can tell, it isn't accessible from the outside to begin with. Am I missing something from a data visibility perspective.

It's not that the counter variable isn't accessible from outside the function to begin with, it's that it is accessible to the increment and print functions after create function has exited that makes closures so useful.

answered 2009-06-03T21:42:06.003
1

Christian Heilmann has a fairly decent article on the module pattern that you describe that might help you wrap your head around it and why it's useful.

answered 2009-06-03T21:40:47.410
1

This syntax makes more sense to me coming from an OOP background:

Create = function {
  // Constructor info.

  // Instance variables
  this.count = 10;
}

Create.prototype = {

     // Class Methods
     sayHello : function() {
          return "Hello!";
     },

     incrementAndPrint : function() {
          this.count++;

          // Inner method call.
          this.print();
     },

     print : function() {
         return this.count;
     }


}

var c = new Create();
alert(c.incrementAndPrint());
answered 2009-07-31T08:09:10.107

Your Answer