Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / Javascript
Tip/Trick

JavaScript patterns simplified

Rate me:
Please Sign up or sign in to vote.
4.78/5 (32 votes)
14 Oct 2014CPOL2 min read 52.5K   35   29
Presents 4 JavaScript patterns

Introduction

JavaScript language exists since 1995 (if I am not mistaken) and it was always a language of choice for the web client-side development. The language is very simple to learn and start writing code but it's not easy to become an expert. One of the reasons is that JavaScript is a dynamic language and because of that there are multiple ways to do the same things. It's easy to write a spagetti code which makes it much harder to maintain later. 

One of the ways to make a code in any language more maintainable is to use design patterns and JavaScript is no exception. There are a lot of article describing the JavaScript patterns and I am not claiming to re-invent a wheel. I just thought it could be a good idea to list some of them in one place and provide a short explanation and an implementation.

There are 4 basic patterns in JavaScript:

  • Prototype pattern
  • Module pattern
  • Revealing Module pattern
  • Revealing Prototype pattern

Prototype pattern

  • Leverages intrinsic JavaScript functionality
  • Comprised of a constructor and a prototype
  • Provides extension capabilities
  • Properties are shared across all object instances, that includes any "private" variables.
JavaScript
// Define a class like this
function Person(name) {
   // Add object properties like this
   this.name = name;
}
// Add methods like this.  All Person objects will be able to invoke this
Person.prototype.speak = function() {
    alert('Hi, my name is ' + this.name);
}
// Instantiate new objects with 'new'
var person = new Person('John');
// Invoke methods like this
person.speak();

Module pattern

  • Provides encapsulation of variables and functions
  • Provides a way to add visibility (public versus private) to members
  • Each object instance creates new copies of functions in memory
  • Extending objects can be difficult since no prototyping is used
JavaScript
// Define a class like this
function Person() {
    // Add methods like this.  All Person objects will be able to invoke this
    this.speak = function speak(name) {
        alert('Hi, my name is ' + name);
    }
}
// Instantiate new objects with 'new'
var person = new Person();
// Invoke methods like this
person.speak('John');

Revealing Module pattern

  • Provides encapsulation of variables and functions
  • Provides a way to add visibility (public versus private) to members
  • Cleaner way to expose public members compared to Module pattern
  • Extending objects can be difficult since no prototyping is used
JavaScript
// Define a class like this
function Person() {
    // Add methods like this. This is a private method
    var speak = function speak(name) {
        alert('Hi, my name is ' + name);
    }
    
    // Return public methods when this object is instantiated. All Person objects will be able to invoke this
    return {
        say: speak
      };
}
// Instantiate new objects with 'new'
var person = new Person();
// Invoke methods like this
person.say('John');
person.speak('John'); // undefined

Revealing Prototype pattern

  • Provides encapsulation of variables and functions
  • Combines the best parts of the Prototype pattern and the Revealing Module pattern
  • Provides a way to add visibility (public versus private) to members
  • Provides extension capabilities
// Define a class like this
function Person(name) {
   // Add object properties like this
   this.name = name;    
}
   
// Add methods like this
Person.prototype = function() {
    // Private method
    var speak = function() {
        alert('Hi, my name is ' + this.name);
    };
    // Public method
    return {
        say: speak
    };
}(); // Execute the function for the prototype to become the returned object 

// Instantiate new objects with 'new'
var person = new Person('John');
// Invoke methods like this
person.say();
person.speak(); // undefined

Hopefully, reading this will help you to write a better code which will be much easier to maintain.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionrevealing module pattern Pin
borchef16-Oct-14 23:35
borchef16-Oct-14 23:35 
AnswerRe: revealing module pattern Pin
Igor Vigdorchik17-Oct-14 6:01
Igor Vigdorchik17-Oct-14 6:01 
GeneralMy vote of 4 Pin
Jhonathan Izquierdo15-Oct-14 11:35
Jhonathan Izquierdo15-Oct-14 11:35 
GeneralRe: My vote of 4 Pin
Igor Vigdorchik15-Oct-14 13:19
Igor Vigdorchik15-Oct-14 13:19 
Generalgreat Pin
snmzkyz15-Oct-14 2:19
snmzkyz15-Oct-14 2:19 
GeneralRe: great Pin
Igor Vigdorchik15-Oct-14 3:13
Igor Vigdorchik15-Oct-14 3:13 
QuestionWhy don't you talk about drawbacks? Pin
Rob Paveza14-Oct-14 10:13
Rob Paveza14-Oct-14 10:13 
AnswerRe: Why don't you talk about drawbacks? Pin
Alexandro Ramos Rodríguez14-Oct-14 11:04
Alexandro Ramos Rodríguez14-Oct-14 11:04 
D'Oh! | :doh: ...
I see that there was something misunderstood.

the "===" operator means "Same instance"

Therefore:
JavaScript
var p = new Person();
var q = p;
var r = new Person();
window.alert( "p.constuctor === Person is " + (p.constuctor === Person) );// false
window.alert( "p instanceof Person is " + (p instanceof Person));// true
window.alert( "p === q is " + (p === q));// true
window.alert( "q === r is " + (q === r));// false


That you said about memory is valid, but you can implement a "Design Pattern", for example a Singleton to save memory.
Usually JS scripts lacks of good and optimum design; and grows ruleless across the web pages despite the thousand JS frameworks.

Particularly, I want to focus over ExtJS, that currently is very lightweight that previously, but for a JS file, over a 1MB is not God sent in web terms.

ExtJS have several fixes to IE memory management leaks.

In response to your question
Quote:
I'd love to see more information about why to use one pattern over another

I quote the article. To me seems clear. The "drawbacks" is about how you implement it, how do you code. Therefore there are any "Use this in this situation" but just are hints to avoid bad practices and issues as make a page loads slow due thousands of unused js tasks or run out memory.

Prototype pattern

Leverages intrinsic JavaScript functionality
Comprised of a constructor and a prototype
Provides extension capabilities
________________________________
Module pattern

Provides encapsulation of variables and functions
Provides a way to add visibility (public versus private) to members
Each object instance creates new copies of functions in memory
Extending objects can be difficult since no prototyping is used
________________________________
Revealing Module pattern

Provides encapsulation of variables and functions
Provides a way to add visibility (public versus private) to members
Cleaner way to expose public members compared to Module pattern
Extending objects can be difficult since no prototyping is used
________________________________
Revealing Prototype pattern

Provides encapsulation of variables and functions
Combines the best parts of the Prototype pattern and the Revealing Module pattern
Provides a way to add visibility (public versus private) to members
Provides extension capabilities

Regards!! Poke tongue | ;-P
AnswerRe: Why don't you talk about drawbacks? Pin
Igor Vigdorchik14-Oct-14 12:55
Igor Vigdorchik14-Oct-14 12:55 
GeneralRe: Why don't you talk about drawbacks? Pin
Member 973967815-Oct-14 10:39
Member 973967815-Oct-14 10:39 
GeneralRe: Why don't you talk about drawbacks? Pin
Igor Vigdorchik15-Oct-14 13:18
Igor Vigdorchik15-Oct-14 13:18 
QuestionNice article Pin
Member 973967814-Oct-14 8:32
Member 973967814-Oct-14 8:32 
AnswerRe: Nice article Pin
Igor Vigdorchik14-Oct-14 9:27
Igor Vigdorchik14-Oct-14 9:27 
GeneralMy vote of 5 Pin
Alexandro Ramos Rodríguez14-Oct-14 7:29
Alexandro Ramos Rodríguez14-Oct-14 7:29 
GeneralRe: My vote of 5 Pin
Igor Vigdorchik14-Oct-14 9:30
Igor Vigdorchik14-Oct-14 9:30 
QuestionNeeds to clarification for multiple functions Pin
jcwren14-Oct-14 7:22
jcwren14-Oct-14 7:22 
AnswerRe: Needs to clarification for multiple functions Pin
Igor Vigdorchik14-Oct-14 9:58
Igor Vigdorchik14-Oct-14 9:58 
GeneralGood Pin
Matthias Engelhardt13-Oct-14 19:30
Matthias Engelhardt13-Oct-14 19:30 
GeneralRe: Good Pin
Igor Vigdorchik14-Oct-14 7:00
Igor Vigdorchik14-Oct-14 7:00 
QuestionNice article, might want to alert readers to scope of variables Pin
Robert Slaney13-Oct-14 15:35
Robert Slaney13-Oct-14 15:35 
AnswerRe: Nice article, might want to alert readers to scope of variables Pin
Igor Vigdorchik13-Oct-14 15:52
Igor Vigdorchik13-Oct-14 15:52 
AnswerRe: Nice article, might want to alert readers to scope of variables Pin
Igor Vigdorchik14-Oct-14 16:50
Igor Vigdorchik14-Oct-14 16:50 
QuestionRevealing Module pattern Pin
archippus13-Oct-14 9:39
archippus13-Oct-14 9:39 
AnswerRe: Revealing Module pattern Pin
Igor Vigdorchik13-Oct-14 10:15
Igor Vigdorchik13-Oct-14 10:15 
GeneralRe: Revealing Module pattern Pin
archippus14-Oct-14 0:33
archippus14-Oct-14 0:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.