background preloader

JS Patterns

Facebook Twitter

JavaScript Module Pattern: In-Depth. The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advanced topics, including one which I think is original. The Basics We’ll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) first blogged about it three years ago. If you’re already familiar with the module pattern, feel free to skip ahead to “Advanced Patterns”. Anonymous Closures This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. (function () { // ... all vars and functions are in this scope only // still maintains access to all globals }()); Notice the () around the anonymous function.

Global Import JavaScript has a feature known as implied globals. Luckily, our anonymous function provides an easy alternative. Module Export. Partial Application in JavaScript. Partially applying a function is a, particularly, interesting technique in which you can pre-fill-in arguments to a function before it is ever executed. In effect, partially applying a function returns a new function which you can call. This is best understood through an example: String.prototype.csv = String.prototype.split.partial(/,\s*/); var results = "John, Resig, Boston".csv(); alert( (results[1] == "Resig") + " The text values were split properly" ); In the above case we’ve taken a common function – a String’s .split() method – and have pre-filled-in the regular expression upon which to split. The result is a new function, .csv() that we can call at any point to convert a list of comma-separated values into an array.

Filling in the first couple arguments of a function (and returning a new function) is typically called currying. With that in mind, let’s look at how currying is, roughly, implemented in the Prototype library: This is a good case of using a closure to remember state. Javascript curry function. Javascript-patterns/function-patterns/currying.html at master · shichuan/javascript-patterns. JavaScript Patterns.