Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 12:04
The Power Of Closures - Deferred Object Bindings In jQuery 1.5
$( function(){ ... DOM-ready code ... } );
$.Deferred(
function( deferred ){
// In addition to the script loading, we also
// want to make sure that the DOM is ready to
// be interacted with. As such, resolve a
// deferred object using the $() function to
// denote that the DOM is ready.
$( deferred.resolve );
}
)
$( deferred.resolve );
<!DOCTYPE html>
<html>
<head>
<title>Deferred Object Bindings in jQuery 1.5</title>
<script type="text/javascript" src="../jquery-1.5.js"></script>
<script type="text/javascript">
// Define the girl constructor. This returns a new Girl
// instance, but not in the traditional sense.
function Girl( name ){
// Create a girl singleton.
var girl = {
// Set the name property.
name: name,
// I say hello to the calling person. Notice that
// when this method invokes properties, it calls
// them on the local "girl" instance. This function
// has created a closure with the local context and
// therefore has access to the "girl" instance no
// matter how this method is invoked.
sayHello: function(){
return(
"Hello, my name is " + girl.name + "."
);
}
};
// Return the girl instance. This will be different than
// the actual instance created by the NEW constructor
// called on the Girl class (though no references to the
// NEW-based instance will be captured).
return( girl );
}
// -------------------------------------------------- //
// -------------------------------------------------- //
// Create some girl instances.
var sarah = new Girl( "Sarah" );
var jilly = new Girl( "Jilly" );
// Collect the sayHello methods. By collecting the method
// references, they are no longer bound to their original
// context objects; the closure behavior of the functions,
// however, remains in-tact.
var methods = [
sarah.sayHello,
jilly.sayHello
];
// Loop over the functions to execute them.
$.each(
methods,
function( i, sayHello ){
// Execute the context-less function.
console.log( sayHello() );
}
);
</script>
</head>
<body>
<!-- Left intentionally blank. -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment