One of the first things I look for when reviewing JavaScript code is the proper use (and isolation) of scope.
Which variables are exposed? Which functions live in the global scope? Are the parts of the API I’ll need to actually interface with public?
I don’t equate coding style to coding skill; looking at how someone’s built an application or library does tell me how much forethought they put into design before they begin writing, though. If you take the time to think through your code design before writing it, even if you’re not the best developer in the world, you’re likely someone I’d like to work with.
Closures
JavaScript is one of the few languages where privacy is really strict – if a function is “private” in JavaScript, it really is private. This has advantages and disadvantages.
On the one hand, you can be sure your code is completely isolated away from the rest of the global scope – you’re a good citizen and you don’t muck anything up for the rest of us.
On the other hand, if your code is private it means no one can ever access or manipulate it, whether you want them to or not.
Take this code snippet for example:
( function( window, undefined ) {
var document = window.document;
function awesomeObject() {
var SELF = this,
name = '';
SELF.doCoolStuff = function() {
name = 'cool thing';
// Do something cool
};
SELF.getName = function() {
return name;
};
}
var awesome = new awesomeObject();
awesome.doCoolStuff();
window.console.log( awesome.getName() );
} )( this );
Inside the closure, your code has access to everything it needs to run. Unfortunately, other developers cannot call your functions here! You’ve built up an API – likely a robust one – but the interface part is missing since no one can reach in to your closure and see your functions.
Instead, you could define a wrapper object in the global scope, then extend that object’s methods to expose your methods to the world. Inside your closure, things stay very much the same. Outside of your closure, other developers can interact with your methods, calling or even replacing them as necessary to interact with your application:
( function( window, undefined ) {
window.myApp = window.myApp || {} ;
window.myApp.awesomeObject = function() {
var SELF = this,
name = '';
SELF.doCoolStuff = function() {
name = 'cool thing';
// Do something cool
};
SELF.getName = function() {
return name;
};
};
var awesome = new window.myApp.awesomeObject();
awesome.doCoolStuff();
window.console.log( awesome.getName() );
} )( this );
How do you use closures to isolate (i.e. privatize) your JavaScript code? How do you expose APIs outside of the closures?