Design Patterns in JavaScript
Over the past year or so I’ve been learning about design patterns and finding them incredibly useful. For languages that have interfaces, it’s especially useful. Even though JavaScript doesn’t have such a concept, you can still apply traditional design patterns to the language. As evidence, I’ve begun writing a series over at WebReference covering Design Patterns in JavaScript. I hope everyone enjoys it.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.




7 Comments
Very useful as always. Thanks.
Some minor notes:
1. Parentheses are missing in the first example of MyFactory:
function MyFactory {}
2. Personally I prefer to use closure to prevent direct object instantiation. In my opinion it is more elegant solution. But maybe I am wrong.
function MyFactory(){}
MyFactory.createObject = (function() {
function MyClass() {
this.myproperty = "hello world";
}
return function () {
return new MyClass();
}
})();
Alexei on April 26th, 2006 at 5:36 pm
That’s not a bad solution either. I would say the only issue would be the constant creation/destruction of the same function definition over and over, every time you called createObject().
Nicholas C. Zakas on April 27th, 2006 at 10:23 am
>> constant creation/destruction of the same function definition
I don’t think I understand. The main function expression – =(FunctionExpression)() – is called only once, and returns another anonymous function which is assigned to the "createObject" identifier. The constructor MyClass is therefore created only once, and is available as closure in the returned anonymous function. Which function definition are you referring to?
Julian Turner on April 28th, 2006 at 3:59 am
Nicholas,
Frankly speaking I wanted to ask exactly the same question as Julian.
Alexei on April 28th, 2006 at 8:37 am
You know, I completely missed the last set of parentheses when I first looked at it (thanks Julian). You’re right, Alexei, that works equally as well.
Nicholas C. Zakas on April 28th, 2006 at 1:01 pm
Note that functions having a property named caller is nowhere standardized. Some engines implement that (Mozilla Spidermonkey engine, MS JScript engine) for historical reasons, but others do not (Mozilla Rhino engine, Opera engine).
Martin Honnen on April 30th, 2006 at 11:06 am
That’s a very good comment, Martin. I guess my Opera ignorance shows.
Nicholas C. Zakas on April 30th, 2006 at 12:47 pm
Comments are automatically closed after 14 days.