Closures For The Creation Of Private Variables

This is the use case that really got yesterday's conversation going. In Javascript, when you have an object that has methods, the "this" keyword within those methods dynamically binds to the object providing the context of invocation. Meaning, when you have an object, "O", that has a method, "M", and you invoke M on O - O.M() - the use of "this" within the method M will refer to the object O.

Javascript doesn't have a native concept of private variables. As such, object properties - including all this-scoped properties - are public. That is, they can be accessed and mutated by their environment. Var-scoped variables, on the other hand, are only available to their local execution context. People have started to use var-scoped variables in conjunction with closures in order to force Javascript to allow for some sort of private variable functionality.

In the following demo, notice that the object properties are not actually stored within the object; rather, they are stored in the same context in which the object was created.

<!DOCTYPE html>

<html>

<head>

<title>Closures For Private Variables</title>

<script type="text/javascript">

// I am a class constructor.

function Girl( name, weight ){

// Store the private variables.

var name = name;

var weight = weight;

// Define the girl instance (our Girl constructor is

// more of a factory than it is a constructor).

var girl = {

// I return the name.

getName: function(){

return( name );

},

// I return the weight - I swear!

getWeight: function(){

return( weight - 10 );

}

};

// Return the girl instance.

return( girl );

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// Create a new girl instance.

var katie = new Girl( "Katie", 125 );

// Check to see if the weight property exists in a public

// portion of the girl instance.

console.log(

"Weight in?",

("weight" in katie)

);

// Get the weight using the accessors.

console.log(

"Weight is:",

katie.getWeight()

);

</script>

</head>

<body>

<!-- Intentionally left blank. -->

</body>

</html>

In the above code, the functions getName() and getWeight() - which are method on the girl object - don't actually refer to properties of "girl"; rather, they refer to variables that have been declared in the same context. Because the getName() and getWeight() functions form closures to the defining context, they will continue to have access to the name and weight variables even after the girl object has been passed out of scope.

When we run the above code, we get the following console output:

Weight in? falseWeight is: 115

As you can see, "weight" does not appear as a public property of the girl instance; but, the getWeight() closure provides access to the original local scope of the Girl() constructor. As such, the local scope of the constructor acts as a sort of make-shift private variables scope.

The caveat with this is that the accessor functions are now lexically bound to the "private" scope and dynamically bound to the girl object. This means that if you need to swap out a function or dynamically build an object, you can end up with methods that don't consistently reference the "right" object. Of course, I put "right" in quotes because if you do understand closures fully, you'll know what you're doing. If you don't understand closures, however, things can get very sticky very fast.

Closures For Use In External Callbacks

Sometimes, when we have an object that has methods, we want those methods to be invoked at a later time, such as in a callback. Our first impulse might be simply pass the method reference to the callback; the problem with this, however, is that a method's context is bound dynamically at invocation time. This means that a method, passed on its own, does not retain any binding to its original object context.

To get around this, we can use a closure that statically binds a given method to a given context. In the following code, notice that we are binding the method sayHello() to a specific instance of girl. In doing so, we create a method that can be passed around on its own.

<!DOCTYPE html>

<html>

<head>

<title>Closures For Callbacks - Method Binding</title>

<script type="text/javascript">

// I am a class constructor.

function Girl( name ){

// Store the public properties.

this.name = name;

// I say hello.

this.sayHello = function(){

console.log( "Hello, my name is " + this.name );

};

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// I create a function that statically binds the given

// method to the given instance.

function bind( instance, method ){

// Create the parent function.

var invocation = function(){

return(

method.apply( instance, arguments )

);

};

// Return the invocation binding.

return( invocation );

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// Create a new girl instance.

var katie = new Girl( "Katie" );

// Now, create a timer that will ask katie to say hello after

// a short delay.

setTimeout(

bind( katie, katie.sayHello ),

1000

);

</script>

</head>

<body>

<!-- Intentionally left blank. -->

</body>

</html>

In this code, the sayHello() method makes use of the "this" keyword, which as we said before, is dynamically bound to the object on which the method is invoked. In order to get "this" to point to our girl object, we need to create a closure that captures both the object reference and the method reference and then knows how to invoke one on the other.

In our case, we created a method, bind(), which takes those two references - object and method - and then returns a function closure that invokes the method in the context of the object. This resultant closure can then be passed around without any external object reference.

When we run the above code, we get the following console output:

Hello, my name is Katie

As you can see, the "this" reference within the sayHello() method was bound to the "katie" instance.

Closures For Use In External Callbacks - Part II

The previous example is definitely cool; but, it statically binds an actual function reference to a context object. While this might be perfect most of the time, it can paint us into a corner. If we changed the implementation of our object - decorating a method for example - a callback bound to a specific function reference might end up invoking the wrong method.

We can take this approach and make it more flexible by binding the context object to a method name rather than a method reference. In this way, we can allow the underlying method implementation to change without having to worry about any out-dated method references.

<!DOCTYPE html>

<html>

<head>

<title>Closures For Callbacks - Method Name Binding</title>

<script type="text/javascript">

// I am a class constructor.

function Girl( name ){

// Store the public properties.

this.name = name;

// I say hello.

this.sayHello = function(){

console.log( "Hello, my name is " + this.name );

};

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// I create a function that statically binds the given

// method name to the given instance.

function bind( instance, methodName ){

// Create the parent function.

var invocation = function(){

return(

instance[ methodName ].apply( instance, arguments )

);

};

// Return the invocation binding.

return( invocation );

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// Create a new girl instance.

var katie = new Girl( "Katie" );

// Now, create a timer that will ask katie to say hello after

// a short delay.

setTimeout(

bind( katie, "sayHello" ),

1000

);

</script>

</head>

<body>

<!-- Intentionally left blank. -->

</body>

</html>

In the above code, notice that we are passing the method name, not the method reference, to the bind() function. Then, the defined closure invokes the method using the name:

instance[ methodName ].apply( instance, arguments )

When we run the above code, we get the following console output:

Hello, my name is Katie

As you can see, it's the same exact result; but, this time, we have built a much higher degree of flexibility into the static binding. We've created a connection that relies on an API rather than an implementation.

Closures For Use In Internal Callbacks

In the above examples, we had an environment that needed to invoke methods on a given object. When it comes to complex objects, however, we will often run into situations in which an object itself needs to define internal callbacks (think event handlers in a HTML UI View Controller). To accomplish this, we could use the same approach - a bind() method. Another often-used approach for complex objects is to simply create a local reference to the "this" scope of the current object.

Because "this" references are dynamically bound at the time of invocation, you'll often see code that creates local variables that point to the current "this" scope:

var self = this;

var that = this;

var _this = this;

All of these create a local variable that is bound to the current this-context. This is done because any function subsequently declared in the same context creates a closure with the same local scope. As such, any function subsequently declared in the same context then has access to the "self" variable regardless of the method's actual "this"-based binding at the time of invocation. This allows an easy way to bind to the method to the defining context without having to create an additional closure (ie. bind).

<!DOCTYPE html>

<html>

<head>

<title>Closures For Internal Callbacks</title>

<script type="text/javascript">

// I am a class constructor.

function Girl( name ){

// Create a local reference to "this"; since this is

// bound dynamically, we need a static verion for the

// this which referes to the current instance.

var self = this;

// Store the name property.

this.name = name;

// I say hello.

this.sayHello = function(){

return( "Hello, my name is " + this.name );

};

// Call a timer to say hello in a bit.

setTimeout(

function(){

console.log( self.sayHello() );

},

1000

);

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// Create an instance of the girl.

var katie = new Girl( "Katie" );

</script>

</head>

<body>

<!-- Intentionally left blank. -->

</body>

</html>

As you can see in the above code, we define a "self" variable in the object constructor. Then, when we create an internal callback for the setTimeout() function, our callback makes reference to self, rather than this:

console.log( self.sayHello() );

When we run the above code, we get the following console output:

Hello, my name is Katie

As I said before, this approach allows us to maintain a reference to the appropriate object even though the "this" reference within the setTimeout() function no longer points to the "intended" context.

Closures For Use In Binding Any Function Any Time

Up until now, our bind() method has always been a stand-alone method. Some Javascript libraries, I believe, actually take the bind concept and add it to the core Function prototype. That is, they build the idea of bind into the very nature of every function. This allows any function to be bound to any context at any time (unless you try to doubly-bind a function - that will mess you up!!).

<!DOCTYPE html>

<html>

<head>

<title>Closures For Core Function Binding</title>

<script type="text/javascript">

// I augment the core function prototype - that from which

// all other functions inherit - to include a bind() method

// which will bind the given functions execution to the

// given context.

Function.prototype.bind = function( context ){

// Get a reference to the current method.

var method = this;

// Define a function that defines the local method

// reference to be executed in the given context.

var invocation = function(){

return(

method.apply( context, arguments )

);

};

// Return the invocation binding.

return( invocation );

};

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// I am a class constructor.

function Girl( name ){

// Store the name property.

this.name = name;

// I say hello.

this.sayHello = function(){

return( "Hello, my name is " + this.name );

};

// Call a timer to say hello in a bit. Notice that the

// callback we are defining is being bound to the THIS

// of the current instance.

setTimeout(

function(){

console.log( this.sayHello() );

}.bind( this ),

1000

);

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// Create an instance of the girl.

var katie = new Girl( "Katie" );

</script>

</head>

<body>

<!-- Intentionally left blank. -->

</body>

</html>

In this code, notice that I am augmenting the Function prototype to contain a bind() method. In doing this, I then allow my anonymous functions to present a bind() API. The idea is exactly the same as before; the difference is that our bind() method is now internal rather than external, so to speak.

When we run the above code, we get the following console output:

Hello, my name is Katie

As you can see, by calling bind() on the anonymous function itself, we were able to get it to execute in the context of the katie object.

Closures For The Creation Of Local Memory Scopes

I sort of hesitate to call this a "closure" since the function we're dealing with never actually gets passed out of the defining scope; but, the function does have a combination of local variables and contextual variables which makes me feel good about bringing it up in this review. In the following code, we are using a self-executing function block in order to create a contained execution context.

<!DOCTYPE html>

<html>

<head>

<title>Closures For Local Memory Spaces</title>

<script type="text/javascript">

// Loop from 1 to 5 to log something to console.

for (var j = 1 ; j <= 5 ; j++){

// After a brief delay, log the j value.

setTimeout(

function(){

console.log( "j :", j );

},

500

)

}

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// -------------------------------------------------- //

// Loop from 1 to 5 to log something to console.

for (var i = 1 ; i <= 5 ; i++){

// Create and invoke a function to create a local memory

// space.

(function( iLocal ){

// After a brief delay, log both i and iLocal values.

setTimeout(

function(){

console.log(

"i :", i,

" - iLocal :", iLocal

);

},

500

);

})( i );

}

</script>

</head>

<body>

<!-- Intentionally left blank. -->

</body>

</html>

As you can see here, I am running two for-loops. In the first one, I create a timed callback to log the value of the iteration index. In the second one, I am doing the same thing; but, this time, I am defining the callback inside of a self-executing function block.

As you can see, the first for-loop results in the same value being logged 5 times. This is because each callback in the first for-loop binds to the same variable, which is "6" at the time in which the setTimeout() callback executes.

The latter for-loop, on the other hand, successfully logs the intended index value using "iLocal." iLocal is the binding of "i" to the argument used to invoke the self-executing function. As a closure, the anonymous function is still bound to the "i" variable which gets logged uniformly as "6" to the console; but, the local scope provided by the function block allows us to bind the internal execution context to the appropriate value of the for-loop.

Closures are insanely bad-ass and they allow us to do some really awesome things. This exploration is in no way complete - but, I hope it helps get you excited about closures and about the kinds of functionality that they can facilitiate.

Say you're testing something which accesses a payment vendor, but in automated testing, you only want to prove that you've gotten to the method that calls the payment vendor, because you're not crazy and you want to test your payment stuff separately.

Assuming this is your existing business class for talking to payment vendor:

function Payment() {

...

this.callVendor = function (args) {...};

};

...

this.payNow = function(args) {...; this.callVendor(); };

return this;

}

Now, to test that you got there, say you were using this class for your test...

function TestClass() {

return this;

}

Now you want to add a test for payNow().

TestClass.prototype.testPayNow = function () {

var callVendorCalled = false;

paymentObj = new Payment();

paymentObj.callVendor = function (args) { callVendorCalled = true; };

paymentObj.payNow(...);

this.assertTrue(callVendorCalled,"Verify callVendor was called...");

}

This is obviously a bit of a pseudo-code example, but I think it's a great use case for closures in automated testing using JavaScript.

Now the question is when will the GPL include runtime augmentation as violations of their original copyright.

@Ben,

How can you explore closures and totally forget to talk about the Module pattern? I'm no expert, but my 15second study of YUI3 made me think they invented a whole new framework to take advantage of Modules and closures in general.

I'm not 100% sure how you would define the Module pattern; I had assumed (quite possibly incorrectly) that the private variables example illustrated what the Modula pattern was. Of course, if you asked me to define the Module pattern, I couldn't... let me look it up :)

I'm having a hard time finding the actual definition via Google, but it looks like the module patterns requires the use of an anonymous function. So, in that regard, I didn't fit the bill as my private variables example uses a names, "constructor"-esque function.

But really, I don't know enough about that stuff to say one way or the other. And then, when you get into the "Require"-style stuff where you are returning factory methods... I think that might be related to the Module pattern as well. But, Require is a whole other ball game that I haven't set gotten into.

Man, I realllly need to look into Require soon; I get the feeling there's a mountain of gold at the end of that rainbow.

It is perhaps a more prototypal closure example, with the absence of 'new' and use of init() instead of a constructor. It's sort of a Singleton on steriods. The goal was/is to use closures to provide a private namespace only available to the object's methods and to differentiate b/t the public and private API.

The extension to this is the revealing module pattern. This one is a bit excessive, where you expose some private methods but do not let end users modify the methods, as so.

I know this is going to sound crazy - and I admit that it is completely emotional - but I can't stand when people define objects inside of a return() statement. There's something about that approach that hurts the readability for me. I see it happen all of the place, so I guess it's a generally-liked practice; but it throws my caveman brain off.

I think what happens is that I get to the return() statement and my brains goes:

"Oh cool - a return statement - all of the heavy lifting must have already been done!"

... and them blam! The return statement itself is doing a whole lot of stuff. Maybe I some sort of reading disorder that simply doesn't like to parse things that way? That's why you see I always define a complex return statement before I return it.

Ok, mini rant aside, the revealing module pattern looks interesting. I am not sure I quite see a use-case for a public/private method? Although, I guess it gives you a chance to add intermediary logic like data-bind-triggering or something?

The question isn't anything to do with your code. It's a question of when GPL will recognize dynamic augmentation that you are using on your third party libraries that may or may not allow rewriting of their source.

@Ben,

It does make the code less readable. It's a matter of maintaining the old fashion ways of true private and public methods. I'm sure there's a reason for them, but I've never used them in my code before.

It's a function the way *I* write it, return(snarkyComeback); :D But yeah, sometimes it's hard to know when something is a function vs. when it's a keyword.

@Drew,

I think you can achieve the same thing with an intermediary variable. I think the only difference is whether you have a named reference to the object being created prior to its return statement. Functionally speaking, I don't think there's a difference.

Thanks for posting ..i understand your all programs . whats happening in this but i have one doubts from long time so in your program's can you explain me where the clouser are used means show me the point where is it...