Javascript – Revealing Module Pattern

This Javascript pattern allows you to define a piece of code with a private scope but have it accessible with a public method. Easy to implement and simple to understand.
<blockquote><code>
var createWorker = function() {</code>

var task1 = function() {
console.log(“moo1”);
}

var task2 = function() {
console.log(“moo2”);
}

return {
job1: task1,
job2: task2
}
}

var worker = createWorker();

worker.job1();</blockquote>
<code>task1</code> and <code>task2</code> functions are confined to the scope of the <code>createWorker</code> function.

In order to make them public to the outside scope, the <code>return<code> method ties public accessors to the inner scoped functions.</code></code>

<code>worker.job1();</code> calls job1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s