Self-Executing Anonymous Function vs Prototype
- by Robotsushi
In Javascript there are a few clearly prominent techniques for create and manage classes/namespaces in javascript.
I am curious what situations warrant using one technique vs. the other. I want to pick one and stick with it moving forward.
I write enterprise code that is maintained and shared across multiple teams, and I want to know what is the best practice when writing maintainable javascript ?
I tend to prefer Self-Executing Anonymous Functions however I am curious what the community vote is on these techniques.
Prototype :
function obj()
{
}
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
Self-Closing Anonymous Function :
//Self-Executing Anonymous Function
(function( skillet, $, undefined ) {
//Private Property
var isHot = true;
//Public Property
skillet.ingredient = "Bacon Strips";
//Public Method
skillet.fry = function() {
var oliveOil;
addItem( "\t\n Butter \n\t" );
addItem( oliveOil );
console.log( "Frying " + skillet.ingredient );
};
//Private Method
function addItem( item ) {
if ( item !== undefined ) {
console.log( "Adding " + $.trim(item) );
}
}
}( window.skillet = window.skillet || {}, jQuery ));
//Public Properties
console.log( skillet.ingredient ); //Bacon Strips
//Public Methods
skillet.fry(); //Adding Butter & Fraying Bacon Strips
//Adding a Public Property
skillet.quantity = "12"; console.log( skillet.quantity ); //12
//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) {
//Private Property
var amountOfGrease = "1 Cup";
//Public Method
skillet.toString = function() {
console.log( skillet.quantity + " " +
skillet.ingredient + " & " +
amountOfGrease + " of Grease" );
console.log( isHot ? "Hot" : "Cold" );
};
}( window.skillet = window.skillet || {}, jQuery ));
//end of skillet definition
try {
//12 Bacon Strips & 1 Cup of Grease
skillet.toString(); //Throws Exception
} catch( e ) {
console.log( e.message ); //isHot is not defined
}
I feel that I should mention that the Self-Executing Anonymous Function is the pattern used by the jQuery team.
Update
When I asked this question I didn't truly see the importance of what I was trying to understand. The real issue at hand is whether or not to use new to create instances of your objects or to use patterns which do not require constructors of the use of the new keyword.
I added my own answer, because in my opinion we should make use of patterns which don't use the new keyword.
For more information please see my answer.