| By Michael Girouard | Article Rating: |
|
| August 25, 2008 07:52 AM EDT | Reads: |
8,987 |
Mike Girouard's Blog
I would like to begin this special series in the run-up to AJAXWorld RIA Conference & Expo in October with one of the most useful and commonplace patterns in my code. Arguably, this can be considered a feature of the JavaScript language rather than a design pattern; however, when considering the contexts in which it is applied, I regard it as a pattern. Self-invocation (also known as auto-invocation) is when a function executes immediately upon it’s definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.
Motivation
The primary motivation behind self-invoking functions is to create scope. In JavaScript, only functions have scope. Any time variables are defined outside of a function, they are carelessly dumped into the global object.
Implementation
A self-invoking function is a standard function, just with a set of parentheses appended to the end.
function () {
var foo = 'Hello';
var bar = 'world';
var baz = [foo, bar];
alert(baz.join(', '));
}();
The above example defines an anonymous function. This creates a literal function, yet since no name is attributed to it, the value is never stored. The trailing parenthesis tell the function to execute, just as if you were calling a named function.
Upon execution, the above function creates three variables, formats them, and alerts them to the user. Once the function terminates, the variables are discarded and the global object remains unchanged.
Distinguishing from Actual Functions
Given the oddness of the pattern (and lack of widespread understanding), it is very possible for developers to misinterpret this pattern as an actual function. It it recommended that an extra set of parentheses wrap the function definition as well so to provide a visual clue to the developer that the function isn’t a normal function. The result would be as follows.
(function () {
var foo = 'Hello';
var bar = 'world';
var baz = [foo, bar];
alert(baz.join(', '));
})();
Passing Parameters
In the event where a self-invoking function requires parameters, they can be passed in the same manor that you would a regular function.
The following example applies an “negative” class on every input element who’s numeric value is below 0.
(function (elements) {
for (var i = 0; i < elements.length; i++) {
if ((elements[i].value * 1) < 0) {
elements[i].className = 'negative';
}
};
})(document.getElementsByTagName('input'));
Executing in Another Scope
Even though the function is executing within its own local scope, the this keyword will still refer to the global object.
The following example uses the Function.call() method to execute a self-invoking function within the scope of the first table element on the page.
(function (elements) {
for (var i = 5; i < this.rows.length; i++) {
this.rows[i].className = 'hide';
}
}).call(document.getElementsByTagName('table')[0]);
Conclusion
In an effort to protect the global object, all JavaScript applications should be written within a self-invoking function. This will create an application scope in which variables can be created without the fear of them colliding with other applications.
If a global variable is needed, developers must take the extra step by setting them directly within the window object. For example window.foo = ‘bar’;.
Self-invocation is a fundamental pattern of professional JavaScript development. Nearly every pattern in this weeks catalog uses it as a base to create scope, closure, or to configure cross-platform objects on-the-fly.
Published August 25, 2008 Reads 8,987
Copyright © 2008 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Michael Girouard
Mike Girouard is a front-end web developer living in New York City. As the Sr. Developer at the creative agency Magnani Caruso Dutton, he takes pride in his ability to introduce web standards and beautiful code to industry giants such as Discover and AT&T. In his offtime, Girouard goes right back to his editor and codes toward his latest open-source baby, Panda PHP Components. You can read more about him and his other projects on his blog, http://www.lovemikeg.com/blog.
- IDEs Belong in the Cloud
- ActiveState Releases Komodo 7, "World's Fiercest IDE"
- eXo Platform 3.5 Now Available: First Cloud-Ready Enterprise Portal and User Experience Platform-as-a-Service (UXPaaS)
- Salesforce.com Announces the Availability of D&B Company Information in Data.com
- Blog Summary for Week of February 6
- MercadoLibre Deploys Opscode Chef® to Automate its OpenStack Private Cloud
- AppFog Enhances User Experience With Additional Add-On Partners Blitz.io and Iron.io
- CloudBees Reduces Cost to Run Java Applications by 62 Percent
- PatientsLikeMe Contributes Free Open-Source Parser to Blue Button Initiative
- BET and CENTRIC Pay Tribute to the Richness and Diversity of the African-American Experience With a Lineup of Dynamic Programming During Black History Month
- Brookfield Homes Calgary Partners with Interior Designer and TV Personality Jillian Harris
- LAN Takes Flight with Opscode for Data Center Automation
- IDEs Belong in the Cloud
- ActiveState Releases Komodo 7, "World's Fiercest IDE"
- eXo Platform 3.5 Now Available: First Cloud-Ready Enterprise Portal and User Experience Platform-as-a-Service (UXPaaS)
- Salesforce.com Announces the Availability of D&B Company Information in Data.com
- Blog Summary for Week of February 6
- MercadoLibre Deploys Opscode Chef® to Automate its OpenStack Private Cloud
- AppFog Enhances User Experience With Additional Add-On Partners Blitz.io and Iron.io
- CloudBees Reduces Cost to Run Java Applications by 62 Percent
- PatientsLikeMe Contributes Free Open-Source Parser to Blue Button Initiative
- BET and CENTRIC Pay Tribute to the Richness and Diversity of the African-American Experience With a Lineup of Dynamic Programming During Black History Month
- Brookfield Homes Calgary Partners with Interior Designer and TV Personality Jillian Harris
- LAN Takes Flight with Opscode for Data Center Automation
- Why Do 'Cool Kids' Choose Ruby or PHP to Build Websites Instead of Java?
- Ruby on Rails Won't Make It in 2007 and Forget About AJAX
- The Jury's Still Out On Ruby On Rails (RoR) and AJAX
- The Top 250 Players in the Cloud Computing Ecosystem
- Red Hat Named "Platinum Sponsor" of Virtualization Conference & Expo
- Ruby on Rails Creator Says: "Reduce the Risk, Hire Programmers From Open Source"
- Java Kicks Ruby on Rails in the Butt
- Can Ruby Live Without Rails?
- An Introduction to Ant
- Testing in Ruby on Rails
- 4th International Cloud Computing Conference & Expo Starts Today
- Cloud Expo 2011 East To Attract 10,000 Delegates and 200 Exhibitors


















