Welcome!

Release Management Authors: Pat Romanski, Elizabeth White, David H Deans, Liz McMillan, Jnan Dash

Related Topics: Release Management , Microsoft Cloud, Machine Learning

Release Management : Article

AJAXWorld RIA Conference - Speaker Mike Girouard's JavaScript Design Patterns, #1

Self-invocation - one of the most useful and commonplace patterns

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.

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.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER gives detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPOalso offers sp...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...