Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Are Some Examples of Design Pattern Implementations Using JavaScript?

I'm a moderately skilled programmer using JavaScript but I am no guru. I know you can do some pretty powerful things with it, I just haven't seen much other than fairly basic DOM manipulation. I'm wondering if people could provide some examples of traditional design pattern concepts such as Factory Method, Singleton, etc using JavaScript. In what cases would these patterns be used for on the web?

like image 247
Aaron Avatar asked Aug 23 '08 21:08

Aaron


People also ask

Which design pattern is used in JavaScript?

Prototype Design Pattern in JavaScript The Prototype design pattern relies on the JavaScript prototypical inheritance. The prototype model is used mainly for creating objects in performance-intensive situations. The objects created are clones (shallow clones) of the original object that are passed around.

What is a JavaScript pattern?

What is a Pattern? A pattern is a reusable solution that can be applied to commonly occurring problems in software design - in our case - in writing JavaScript web applications. Another way of looking at patterns are as templates for how we solve problems - ones which can be used in quite a few different situations.


1 Answers

I just wanted to add my favorite JavaScript pattern that I learned from Pro JavaScript Design Patterns which Jonathan Rauch already recommended.

It is the namespace singleton pattern. Basically, you create namespaces via singletons which allow you to hide methods and variables from external use. The hidden/exposed methods are actually hidden because they are defined within the closure.

var com = window.com || {};
com.mynamespace = com.mynamespace || {};
com.mynamespace.newpackage = (function() {
    var myPrivateVariable = "hidden";
    var myPublicVariable = "exposed";

    function myPrivateMethod() {
        return "also hidden";
    }

    function myPublicMethod() {
        return "also exposed";
    }

    return {
        myPublicMethod: myPublicMethod,
        myPublicVariable: myPublicVariable
    };
})();
like image 140
Mike Stone Avatar answered Oct 06 '22 23:10

Mike Stone