A JavaScript Module Pattern
June 12, 2007 at 12:28 pm by Eric Miraglia | In Development |Global variables are evil. Within YUI, we use only two globals: YAHOO and YAHOO_config. Everthing in YUI makes use of members within the YAHOO object hierarchy or variables that are scoped to such a member. We advise that you exercise similar discipline in your own applications, too.
Douglas Crockford has been teaching a useful singleton pattern for achieving this discipline, and I thought his pattern might be of interest to those of you building on top of YUI. Douglas calls this the “module pattern.” Here’s how it works:
1. Create a namespace object: If you’re using YUI, you can use the YAHOO.namespace() method:
YAHOO.namespace("myProject");
This assigns an empty object myProject as a member of YAHOO (but doesn’t overwrite myProject if it already exists). Now we can begin adding members to YAHOO.myProject.
2. Assign the return value of an anonymous function to your namespace object:
YAHOO.myProject.myModule = function () {
return {
myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty.";
myPublicMethod: function () {
YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
}
};
}(); // the parens here cause the anonymous function to execute and return
Note the very last line with the closing curly brace and then the parentheses () — this notation causes the anonymous function to execute immediately, returning the object containing myPublicProperty and myPublicMethod. As soon as the anonymous function returns, that returned object is addressable as YAHOO.myProject.myModule.
3. Add “private” methods and variables in the anonymous function prior to the return statement. So far, the above code hasn’t bought us any more than we could have gotten by assigning myPublicProperty and myPublicMethod directly to YAHOO.myProject.myModule. But the pattern does provide added utility when we place code before the return statement:
YAHOO.myProject.myModule = function () {
//"private" variables:
var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";
//"private" method:
var myPrivateMethod = function () {
YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
}
return {
myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty."
myPublicMethod: function () {
YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
//Within myProject, I can access "private" vars and methods:
YAHOO.log(myPrivateVar);
YAHOO.log(myPrivateMethod());
//The native scope of myPublicMethod is myProject; we can
//access public members using "this":
YAHOO.log(this.myPublicProperty);
}
};
}(); // the parens here cause the anonymous function to execute and return
In the codeblock above, we’re returning from an anonymous function an object with two members. These members are addressable from within YAHOO.myProject.myModule as this.myPublicProperty and this.myPublicMethod respectively. From outside of YAHOO.myProject.myModule, these public members are addressable as YAHOO.myProject.myModule.myPublicProperty and YAHOO.myProject.myModule.myPublicMethod.
The private variables myPrivateProperty and myPrivateMethod can only be accessed from within the anonymous function itself or from within a member of the returned object. They are preserved, despite the immediate execution and termination of the anonymous function, through the power of closure — the principle by which variables local to a function are retained after the function has returned. As long as YAHOO.myProject.myModule needs them, our two private variables will not be destroyed.
4. Do something useful with the pattern. Let’s look at a common use case for the module pattern. Suppose you have a list, some of whose list items should be draggable. The draggable items have the CSS class draggable applied to them.
<!--This script file includes all of the YUI utilities:-->
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.2/build/utilities/utilities.js"></script>
<ul id="myList">
<li class="draggable">Item one.</li>
<li>Item two.</li> <!--item two won't be draggable-->
<li class="draggable">Item three.</li>
</ul>
<script>
YAHOO.namespace("myProject");
YAHOO.myProject.myModule = function () {
//private shorthand references to YUI utilities:
var yue = YAHOO.util.Event,
yud = YAHOO.util.Dom;
//private method:
var getListItems = function () {
//note that we can use other private variables here, including
//our "yud" shorthand to YAHOO.util.Dom:
var elList = yud.get("myList");
var aListItems = yud.getElementsByClassName(
"draggable", //get only items with css class "draggable"
"li", //only return list items
elList //restrict search to children of this element
);
return aListItems;
};
//the returned object here will become YAHOO.myProject.myModule:
return {
aDragObjects: [], //a publicly accessible place to store our DD objects
init: function () {
//we'll defer making list items draggable until the DOM is fully loaded:
yue.onDOMReady(this.makeLIsDraggable, this, true);
},
makeLIsDraggable: function () {
var aListItems = getListItems(); //these are the elements we'll make draggable
for (var i=0, j=aListItems.length; i<j; i++) {
this.aDragObjects.push(new YAHOO.util.DD(aListItems[i]));
}
}
};
}(); // the parens here cause the anonymous function to execute and return
//The above code has already executed, so we can access the init
//method immediately:
YAHOO.myProject.myModule.init();
</script>
This example is a simple one, and it’s deliberately verbose — if this was all we were doing, we could doubtless write it in a more compact way. However, this pattern scales well as the project becomes more complex and as its API grows. It stays out of the global namespace, provides publicly addressable API methods, and supports protected or “private” data and methods along the way.
Share and extend: Bookmark with Yahoo! My Web | Bookmark with del.icio.us | digg it! | reddit!
81 Comments »
RSS feed for comments on this post. TrackBack URI
Leave a comment

Copyright © 2007 Yahoo! Inc. All rights reserved. Privacy Policy - Terms of Service
Powered by WordPress on Yahoo! Web Hosting.
This is such a great article. Especially all of the hullabaloo (sp?) over $ and the conflicts that can be easily created with global objects.
Comment by Ryan — June 12, 2007 #
Eric,
Finally someone explains this pattern in a clear, intelligible way! Thank you, thank you, thank you.
By the way, this looks like the beginning of a book on YUI. When is the rest of the book coming? :-)
Thanks again,
Louis
Comment by louis — June 12, 2007 #
@Louis — You’re most welcome. As for a book on YUI, I think you’ll get your wish, maybe a few times over…there’s certainly publisher and author interest out there in doing YUI titles. For more articles like this one, check out http://crockford.com — Douglas has a lot of great material up on his site. Regards, -Eric
Comment by Eric Miraglia — June 12, 2007 #
Eric,
I have read most articles from Doug, I have watched his videos.
I have read through Flanagan’s Definitive Guide…
I really think your explanations are much better: I read your article and understood everything immediately, and I was not left with many unanswered questions.
Comment by louis — June 12, 2007 #
I’m with Louis. This is very well written for someone to understand and enjoy the benefits this provides.
Thanks for the article
Comment by Dimitry — June 12, 2007 #
I’ll echo everyone’s sentiments so far.
Great article!
Loved the explanations!
Comment by Oliver Tse — June 12, 2007 #
A similar pattern is the “shared singleton” — create a singleton object for an application that can be used to share properties or methods between pages or inline frames.
Here’s the start of a “my.js” script that every page or frame in an application could share:
if (typeof parent.my != “undefined”) {
var my = parent.my; // shared singleton
} else {
var my = {};
my.something …
}
The “parent” bit is so that the script can be used with iframes and still
retain a reference to the same “my” instance. If a page is at the top, then parent points to itself.
Every page or frame that imports “my.js” can share properties or methods with any other page.
-Ted.
Comment by Ted Husted — June 12, 2007 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog […]
Pingback by Daily misery » Blog Archive » Links for 6.12.2007 — June 12, 2007 #
Eric - Just what I needed. Thank you!
Comment by jaymuntz — June 12, 2007 #
I’m going to echo the statements by the rest of the commenters. I never really understood this pattern, merely copied it over and over for it’s elegant design.
After reading this article, the pattern makes much more sense. Thanks again Eric!
Comment by Wayne Pan — June 12, 2007 #
I’ve added a tweak to this pattern from time to time, though it might be gratuitous:
module = function() {
// ... module privates and aliases
return {
// ... module constants
init: function() {
return this;
},
// ... module methods
EOF:null
};
}().init();
This constructs the module, and after construction calls an init() method that has access to the module via this. I use that method to register onload and onavailable handlers for the module, among other things.
Oh, and the EOF:null has saved me from stray extra commas after the last method on a few occasions. Those seem to get a pass in Firefox, but throw errors in MSIE.
Comment by l.m.orchard — June 12, 2007 #
Of course, after having posted that comment, I see that your examples call an init() method too - but maybe with a bit less one-liner obscurity than mine. :)
Comment by l.m.orchard — June 12, 2007 #
Ah so we call it the module pattern…I used to call it “that technique I have seen in many of Dustin Diaz’ screencast”.
I think that ‘module pattern’ will go down much better in an interview situation.
Thanks for this Eric, the news of a possible book is great news!
Comment by Carlton — June 13, 2007 #
I’ve been looking for a good way to explain this to my work colleagues, it’s the pattern we use extensively in our application, and up until now the best explanation I could give them was “It’s kind of like a singleton” which has always met with rather blank looks, and while I think they understand what I was trying to get across, I can now link them to this instead.
Comment by Stuart Grimshaw — June 13, 2007 #
[…] Eric Miraglia, of Yahoo!, has documented his explanation of what Douglas Crockford calls the JavaScript Module pattern. […]
Pingback by Ajax Girl » Blog Archive » A JavaScript Module Pattern — June 13, 2007 #
The start of a great series. I have a few talented java coders who are sort of on standby regarding upgrading their Javascript knowledge. Stuff like this is perfect for me to send to them because it speaks their vocabulary and is presented from a central respected authority.
Can’t wait to see more.
Comment by Ivan — June 13, 2007 #
One quick request. This is effectively a singleton, but it would be helpful to see a similar implementation that describes it as an instance. Thanks again!
Comment by Ivan — June 13, 2007 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog (tags: javascript yui namespace programming oop pattern) […]
Pingback by Web Site Design, Internet Marketing, Ecommerce - ryanj - links for 2007-06-13 — June 13, 2007 #
I have been using this pattern ever since I had heard about it from Doug’s lectures last year, and just have an addition that you may find usefull.
Private methods can access other private methods and variables, but not public methods unless it is a singltoon then you call the full name of the singleton and get those methods, that is more of a hack. Public methods can call private methods and other public methods but you must include this.public method name in order to call other public methods.
This is from my experience with using this pattern and a few others that he had mentioned.
Comment by Don Pavlik — June 13, 2007 #
Brilliant article Eric. This is by far the best explaination of this pattern I have ever read, leaving the reader with no question as to what is happening. Very nice.
My only complaint is the name. I would call this a JavaScript Singleton Pattern. “Module Pattern” is too generic sounding. What is a “module” anyway? You can’t derive from the name that this is really a Singleton.
But I’m certainly willing to forgive the name considering the quality of this article. :-)
Comment by Peter Foti — June 13, 2007 #
Why an instance? If you really must. It’ll probably be something like:
function Module() {
//private stuff
function myprivmethod() {}
//public stuff
this.init() { }
// etc
}
YAHOOO.MyProject.MyModule = new Module();
Comment by jchoe — June 13, 2007 #
[…] Miraglia officially promotes one of the YUI library’s unofficial object creation […]
Pingback by geoffreymoller.com » Blog Archive » Preach the Word - Crockford’s Module Pattern — June 13, 2007 #
[…] Miraglia officially promotes YUI’s unofficial object creation […]
Pingback by geoffreymoller.com » Blog Archive » Preach the Word - Crockford’s Module Pattern — June 13, 2007 #
Instances in this pattern have to be created without new keyword.
I recommend to everyone here to view video by Douglas Crockford - Advanced Javascript.
But I personally like pattern from YUI - Element.
(function() {
// private functions
....
// Constructor
MyGlobalObject.MyClass = function() {
}
// assigning fields and method to global object
MyGlobalObject.MyClass.prototype = {
function1 : function() {},
function2 : function() {}
}
})();
and then you can use new keyword for instances.
I use singleton pattern for static classes and pattern above for all other classes. So in my eyes code looks better.
Comment by Monin Dmitry — June 13, 2007 #
@l.m.orchard
Your code puts the return value of the init function into the module variable.
The object that was returned from the anonymous function is lost.
This is OK if you are doing what most people do which is just copy and paste this with ONE function: init. And just use it as a way to run that function.
But if you are actually using it to produce a useful singleton object, you’d be knackered.
Comment by Animal — June 13, 2007 #
[…] Crockford’s suggestion for how to construct a JavaScript module awhile back. Here is another walk through of the same pattern by Eric Miraglia of Yahoo!. The idea is to provide both public, protected and […]
Pingback by Road Warrior Collaboration » Javascript Module Pattern — June 13, 2007 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog (tags: javascript programming yui pattern namespace oop yahoo dom development designpatterns design coding application private prototype tips toread webdesign webdev work learning js patterns **) […]
Pingback by links for 2007-06-14 « Simply… A User — June 13, 2007 #
[…] sounds a bit peculiar.. it’s good in C, which i heard.. but here it’s a diff world >> No Comments so far Leave a comment RSS feed for comments on this post. TrackBack URI […]
Pingback by error is the mother of all inventions — June 13, 2007 #
This is OK if you are doing what most people do which is just copy and paste this with ONE function: init. And just use it as a way to run that function.
But if you are actually using it to produce a useful singleton object, you’d be knackered.
Comment by tercüme — June 14, 2007 #
Since I, probably like most readers, don’t work at YAHOO, I think it would be a very bad idea for me to put my project under the YAHOO namespace. What if YAHOO adds a YAHOO.myProject object to YUI? “Don’t modify objects you don’t own” is good advice and I don’t own the YAHOO object. We don’t want YAHOO to become the new global namespace and then have conflicts under YAHOO instead of under window object. The idea is that YAHOO stays in its space and I stay in my space.
Comment by Peter Michaux — June 14, 2007 #
Personally, I use this pattern all the time, even when other developers think different, especially when we’re working with collections of references using this pattern to management of each reference.
But I use a variation of the module pattern:
YAHOO.myProject.myModule = function () {
var obj = {}; // returnable object...
//"private" variables:
var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";
//"private" method:
var myPrivateMethod = function () {
YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
YAHOO.log("And also have access to the public and privates properties");
YAHOO.log(obj.myPublicProperty);
}
var obj.myPublicProperty = "I'm accessible as YAHOO.myProject.myModule.myPublicProperty.";
var obj.myPublicMethod = function () {
YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");
//Within myProject, I can access "private" vars and methods:
YAHOO.log(myPrivateVar);
YAHOO.log(myPrivateMethod());
//The native scope of myPublicMethod is myProject; we can
//access public members using "this":
YAHOO.log(this.myPublicProperty);
};
return obj;
}(); // the parens here cause the anonymous function to execute and return
The codeblock above, has exactly the same behavior that the eric code in the article, but also provide an easy way to get access to the public variables and methods within the private block.
In this case, the private variables myPrivateProperty and myPrivateMethod can operate over the public members using the shorthand “obj” instead of the complete name “YAHOO.myProject.myModule”, this pattern also can be used to create a object’s parasites (more information about this pattern in the Douglas Crockford - “Advanced Javascript” Presentation).
@Peter: I’m 100% agree with you…
@Eric: Thanks for everything, keep going ;-)
Comment by Caridy Patiño — June 14, 2007 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog […]
Pingback by runion.cc/ » A JavaScript Module Pattern » Yahoo! User Interface Blog — June 15, 2007 #
Caridy Patino’s comment above makes a good point. If you use the pattern as explained in the blog entry, public methods can’t call other public methods!
Binding each public method to a local var called “obj” which is later returned, will work. Even then I think a method definition must be written before its invocation in the JS file.
Thanks for a useful article.
Comment by Pramod Biligiri — June 15, 2007 #
@all — Thanks for all the great feedback.
@Don — see Caridy’s comment for a tweak that makes the private’s access to public easier, and my thoughts below.
@Ted — Cool idea, thanks for sharing that!
@Peter F. — What if we call it the “Crockford Module Pattern”? Slightly more specific. I think of it as a modular pattern in the sense that it easily encapsulates all the content for a specific piece of functionality. It’s a good generic pattern for developing modular code.
@Peter M. — I take your point. The pattern is independent of the namespacing, though; if you omit the bit about YAHOO.namespace(), you can still leverage the pattern.
@Monin Dmitry — I like the anonymous function pattern, too, and it’s the handiest insulator out there. For my taste, the module pattern scales a little better, but we use both in YUI as you say.
@Caridy — I like it.
@Pramod — I think you mean that you can’t access publics from privates? It’s generally as simple thing to either call the private from the scope of “this” or to pass “this” in as an argument, but you’re right that Caridy’s variation makes that unnecessary.
Comment by Eric Miraglia — June 15, 2007 #
There are dozens of ways to make public stuff visible in private scope, a bit simpler one:
var APP = function(){
var that = {};
function doPrivateStuff(){
that.myMethod();
}
return {
publicMember: true,
myMethod: function(){},
// make this visible in private scope
init(){
that = this;
}
};
}().init();
Comment by nea — June 18, 2007 #
ups, forgot ‘return this;’ at the end of init() :).
Comment by nea — June 18, 2007 #
[…] an addition to the recently named Module Pattern. Let’s add private static class […]
Pingback by Dr. Prolix » Blog Archive » Private static class vars in javascript — June 19, 2007 #
[…] A JavaScript Module Pattern […]
Pingback by Max Design - standards based web design, development and training » Some links for light reading (20/6/07) — June 20, 2007 #
very nice! Does anybody know an editor with a class browser for this classes an methods notation? I found only Komodo supporting this notation.
Comment by Thomas H. — June 21, 2007 #
I will start with an echo of the above comments that applaud this explanation as “finally” explaining something that many of us have known about for a while but did not really “get”.
For those of us that have been using JSAN for a while the idea of using namespaces for our methods is old hat as it is a requirement in that world. A few months back I made a series of posts to ydn-javascript discussing that very topic. Which culminated in a change request for YUI.
From working with JSAN the style I had adopted results in js files similar to
if(typeof self != 'undefined') {
if(typeof com == "undefined" ){com = {};}
if(typeof com.myclass == "undefined" ){com.myclass = {};}
if(typeof com.myclass.foo == "undefined" ){com.myclass.foo = {
func:function(){...}
};}
}
I had seen the approach you describe here but never fully wrapped my head around it. Now I get it, thank you, and going forward I will be taking this direction.
I have one issue though and one question. The issue is with namespaces. It seems every JS lib out there expects developers to house all their code under their own namespace. I do not really follow this logic and since I was doing a lot of work with Java applications when I started with JSAN I adopted a loose version of Sun’s package naming convention. I would love to see that approach spread across JS development as it really seems to make much more sense than YAHOO.myProject.myModule particularly if you ever have any intention of passing your module along for someone else to use.
Going off your example I have no problem using YAHOO.myProject.myModule.myPublicMethod(args) but sometimes there is the desire to use YAHOO.myProject.myModule(args) as well. My question is how to do this. I have never been able to quite sort it out.
Thanks for posting this!
Comment by alek — June 26, 2007 #
[…] A JavaScript Module Pattern: explaining how all this is applied at Yahoo! […]
Pingback by klauskomenda.com » JavaScript Programming Patterns — July 7, 2007 #
[…] not be accessed from outside of the object (if you want to make them truly private, you can use Crockford’s Module Pattern). The _timeoutId property stores a timeout ID that is used to control how often _process(), the […]
Pingback by Downshift Your Code » Yahoo! User Interface Blog — July 9, 2007 #
[…] this approach lacks a few of the features of more sophisticated alternatives, it’s simple enough that beginners can grasp it and feel confident writing their own scripts […]
Pingback by developercast.com » JavaScript: How Simple is Too Simple? — July 10, 2007 #
[…] Eric Miraglia, of Yahoo!, has documented his explanation of what Douglas Crockford calls the JavaScript Module pattern. […]
Pingback by The JavaScript Module Pattern » Fat Agnus — July 16, 2007 #
@Eric, great article, though I prefer using
new function (){}instead of thefunction(){return {/**/};}();approach you describe. Do you have a reason for using one over the other; they both generate an object and allow private and publicly scoped variables?@Peter, great point! I completely agree with you.
@alek, you should take a look at Ajile. It’s a cross-browser solution for JavaScript namespacing I’ve created. It supports the Sun package naming convention you mentioned with the added flexibility of not needing to store scripts in a matching directory structure. Ajile’s also unobtrusive in that it allows you to create standalone namespaces and namespace’d modules that are independent of Ajile’s own namespace. This differs from the YAHOO.namespace approach that wraps created namespaces and then requires using the YAHOO object to reference them and their contained objects.
Comment by Michael Lee — July 25, 2007 #
[…] A JavaScript Module Pattern » Yahoo ! User Interface Blog […]
Pingback by John Noone » J'ai marqué le 16-08-2007 — August 15, 2007 #
[…] 和 Crockford 的模块模式来弥补第一种方法的缺陷。使用闭包可以隐藏全局变量t,只有在 […]
Pingback by Realazy » 惰性函数定义模式 — August 15, 2007 #
Thanks Eric for such a great article, I have been using this technique since YUI release, I borrowed this from YUI definitely but didn’t know the pattern name but now I know it as “Module Pattern”, so from now on I don’t have to tell my fellow developers that it’s a “YUI kinda thing”. Thanks very much :)
Comment by Arnab — August 17, 2007 #
@Arnab — Thanks for the kind words. You make a good point, and others have pointed out that I should have been more clear about this in the piece: This is a generic pattern, not specific to YUI at all. It’s just a pattern, one of several that achieve similar goals, and not related to any particular library. -Eric
Comment by Eric Miraglia — August 17, 2007 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog A reasonable approach for module-like things (including private variables) in JavaScript (tags: javascript) […]
Pingback by Blue Sky On Mars » Blog Archive » links for 2007-08-18 — August 18, 2007 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog A way of organisng javascript properly (tags: javascript) […]
Pingback by Mark Kirby - Brighton » Blog Archive » links for 2007-08-28 — August 28, 2007 #
[…] has the notion of namespaces and packages (which we usually fake on the web) and class-based objects (eww! well, it supports the prototype stuff as well). So if we […]
Pingback by phpied.com » Blog Archive » Make your javascript a Windows .exe — August 31, 2007 #
[…] 或者我所喜欢的”model pattern“: […]
Pingback by Realazy » JavaScript文档生成工具 — September 1, 2007 #
Hate to be the guy to point out code errors, but in Step 3, you forgot a comma after myPublicProperty.
Should be:
myPublicProperty: “I’m accessible as YAHOO.myProject.myModule.myPublicProperty.”,
Other than that, excellent article.
Comment by MacDonald — November 12, 2007 #
[…] どうやったら上のように、そしてYUIっぽく書けるかな、と昨日の晩から調査をしていました。そして、ようやくその手がかりとなるポストを見つけることができました。(別にYUI以外でもこの書き方していいけど。。。) A JavaScript Module Patternです。名前はこのポストの著者のEricさんが勝手に付けたっぽいのですが、いいです。これ。日本でも半年前に話題になっていたみたいですね。時代遅れですいません。 […]
Pingback by GANCHIKU.com » JavaScript Module Patternいいね。半年遅れだけど。。。 — November 14, 2007 #
Just a note: Really great article and with Caridy Patiño’s extension it becomes even more flexible.
Except one little thing:
I got an error when trying to create a public method with “var” keyword:
var obj.init = function() { …
-> missing ; before statement
It only works for me without “var”. Or did i miss something?
Comment by Michael Härtl — November 18, 2007 #
Michael,
varfails in that case becauseobjis already declared. You can dynamically addinittoobj.-Eric
Comment by Eric Miraglia — November 18, 2007 #
This is all very good stuff. Thank you for your post!
I’ve taken a lot of what I’ve seen here and on a couple of other sites and put together what I think is a reasonable solution for me. I’d like to hear what people think about it (as I’m still a relative n00b to javascript, coming most recently from python).
I’ve documented it in my own blog entry. All feedback (here or there) will be greatly appreciated!
Comment by cygnl7 — November 21, 2007 #
[…] easiest trick to make the script work well with others is to use the module pattern and nest it in a variable assigned to an anonymous function […]
Pingback by Wait till I come! » Blog Archive » Transcript of the Paris Web 2007 workshop on Unobtrusive JavaScript — November 23, 2007 #
Eric, where you wrote: “What if we call it the “Crockford Module Pattern”? Slightly more specific. I think of it as a modular pattern in the sense that it easily encapsulates all the content for a specific piece of functionality. It’s a good generic pattern for developing modular code.” you have made a good case for the “Module Pattern” part of the name, but not the “Crockford” part. What is the rational for naming something after the person who told you about it? My school physics teacher might have been quite happy with “Heywood’s general theory of relatively” but traditionally that is not the way things work.
In essence the module pattern is using the (usually inline) execution of a function expression to privately encapsulate all the internal and interrelated parts of an otherwise independent module (function, object, sub-system, etc.). To the best of my knowledge the first examples of that being done are to be found back in April/May 2003 in a comp.lang.javascript Usenet discussion group response to a question asked by Svend Toffe with the subject “closures, what are they good for?”. The following two years witnessed the comp.lang.javascirpt regulars take up the pattern and try out (probably pretty much all of) its permutations, with the ’singleton’ you demonstrated above first appearing in August 2003.
Comment by Richard Cornford — November 24, 2007 #
@Richard — My original suggestion was just to call it “a module pattern” — one of many that work in JavaScript. I do think it’s fair to credit Douglas for spreading the ideas from comp.lang.javascript out to the broader JS-authoring community — he makes no claims about having invented these things, but he’s also been one of the most articulate spokespeople for the best ideas about the language. It’s not for nothing that Brendan Eich called him the “Yoda of JavaScript” last year.
I’m not disagreeing with you, though, and Douglas probably wouldn’t either. I don’t think he advocates this pattern in preference to others, and in general I believe he prefers more uniquely with-the-grain approaches like the parasitic inheritance model he talks about in his Advanced JavaScript video (http://developer.yahoo.com/yui/theater/).
Thanks for the comment and the pointers to the comp.lang.javascript thread — that’s great context for this post.
Comment by Eric Miraglia — November 26, 2007 #
[…] A JavaScript Module Pattern, by Eric Miraglia. […]
Pingback by Indigio Blog - Colorado’s premier Interactive Agency blog - specializing in SEO, Creative Design, Development and Analytics » Blog Archive » JavaScript and the Importance of Namespaces — November 29, 2007 #
[…] that’s the theory anyway. On to the code.First, let’s create a module to contain all this code, along with the public API […]
Pingback by Junction Networks » Blog Archive » Attaching JavaScript Behavior — December 6, 2007 #
[…] a function with a bunch of prototype properties is very, very, fast. It completely blows the Module pattern, and similar, out of the water. Thus, if you have a frequently-accessed function (returning an […]
Pingback by John Resig - Simple "Class" Instantiation — December 6, 2007 #
[…] interesting javascript pattern for handling real public/private […]
Pingback by blog.dknowles.org » Blog Archive » Link post — December 16, 2007 #
[…] [1] YUI Blog JS module pattern […]
Pingback by Why Object-Oriented JavaScript is so confusing | CodeUtopia — December 20, 2007 #
[…] I’m not using one of the Javascript frameworks that provides a notion of packages, but it is easy to roll your own. I follow this Javascript module pattern. […]
Pingback by Why can’t it all be pretty? < Code Monkey Island — January 2, 2008 #
Douglas Crockford is great man, I needed this article, thx
Comment by Smsy — January 10, 2008 #
[…] isn’t so much to ditch Prototype, but to encourage using […]
Pingback by JavaScript namespaces — February 4, 2008 #
[…] A Javascript Module Pattern […]
Pingback by Javascript - Still Object-Oriented :: Darwin Among the Prototypes II: Private Members — February 14, 2008 #
Comment by Caridy Patiño — June 14, 2007 #
Brilliant. Chris Heilman picked up on this and used, “pub”, as I now do (but you could name it anything). It’s a great pattern. Caridy’s comment is where it came from.
Comment by Fside — February 19, 2008 #
[…] article a été publié sur le YUI Blog, qui traite du Module Pattern, ou comment réaliser un singleton en […]
Pingback by Le coin d’Anthony » Blog Archive » Javascript, singleton et Module Pattern… — February 20, 2008 #
Great Article. I love the way of explanations!
Comment by Abi — March 17, 2008 #
[…] source : http://yuiblog.com/blog/2007/06/12/module-pattern/… Posted by lotusnotes Filed in Lotus […]
Pingback by A JavaScript Module Pattern [yuiblog.com] « Lotus Notes — рабочий инструмент программиста. — March 28, 2008 #
Brilliant article Eric. This is by far the best explaination of this pattern I have ever read, leaving the reader with no question as to what is happening. Very nice.
Comment by ekspertiz. degerleme — April 1, 2008 #
The start of a great series. I have a few talented java coders who are sort of on standby regarding upgrading their Javascript knowledge. Stuff like this is perfect for me to send to them because it speaks their vocabulary and is presented from a central respected authority
Comment by Friendzhug — April 6, 2008 #
[…] means to construct durable objects that can perfectly guard their state by using a variation of the Module Pattern. You’ll recall that the Module Pattern makes it possible to make an object with privileged […]
Pingback by Durable Objects » Yahoo! User Interface Blog — May 24, 2008 #
[…] A JavaScript Module Pattern » Yahoo! User Interface Blog (tags: javascript libraries design_patterns reference) […]
Pingback by links for 2008-05-30 « Amy G. Dala — May 30, 2008 #
[…] had cooked up the JavaScript code sample real quick, but you can still see the use of the module pattern (from Douglas Crockford) in the VMAP function. It is always a good practice to follow the module pattern to keep your […]
Pingback by SQL Server 2008 + VirtualEarth made easier and building a REST API « Vish’s ramblings — June 1, 2008 #
[…] The JavaScript Module Pattern […]
Pingback by Book review: JavaScript: The Good Parts - Robert’s talk - Web development and Internet trends — June 4, 2008 #
For those of us that have been using JSAN for a while the idea of using namespaces for our methods is old hat as it is a requirement in that world.
Comment by Etos — June 20, 2008 #