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.
function Person(name) {
this.name = name;
}
Person.prototype.speak = function() {
alert('Hi, my name is ' + this.name);
}
var person = new Person('John');
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
function Person() {
this.speak = function speak(name) {
alert('Hi, my name is ' + name);
}
}
var person = new Person();
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
function Person() {
var speak = function speak(name) {
alert('Hi, my name is ' + name);
}
return {
say: speak
};
}
var person = new Person();
person.say('John');
person.speak('John');
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
function Person(name) {
this.name = name;
}
Person.prototype = function() {
var speak = function() {
alert('Hi, my name is ' + this.name);
};
return {
say: speak
};
}();
var person = new Person('John');
person.say();
person.speak();
Hopefully, reading this will help you to write a better code which will be much easier to maintain.