16
JavaScript Design Patterns JavaScript developers have several options for creating an Object in JavaScript, from the Object() method to Object literals to constructor functions, there are a lot of ways to get the job done. This article will present a few choice Object creation Patterns. Pros and cons of each pattern are also listed. urated by : Gomes, Jijo

Javascript design patterns

Embed Size (px)

DESCRIPTION

discussing most important design patterns like, module,reveal,prototype

Citation preview

Page 1: Javascript design patterns

JavaScript Design Patterns

JavaScript developers have several options for creating an Object in JavaScript, from the Object() method to Object literals to constructor functions, there are a lot of ways to get the job done. This article will present a few choice Object creation Patterns. Pros and cons of each pattern are also listed.

Curated by : Gomes, Jijo

Page 2: Javascript design patterns

Why should we follow a specific design pattern?

- It helps to create modular and functional code

- Unit testable/reusable code since entire programming paradigm shift to client side

Page 3: Javascript design patterns

What is wrong here?

This is a javascript file with a bunch of functions written. There is no proper structure followed. There is a global variable resultCtrl, which means it is not only accessible from the script file but anywhere from the code. Since global variable can be accessed from anywhere in the code, it is very difficult to understand what changes what and when? This code is:-

1. Difficult to understand.2. Difficult to maintain.3. Not re-usable.

So how can we make it more structured? Let's see how can we re-write this code using different design patterns.

Page 4: Javascript design patterns

1. Prototype Pattern

The Prototype Pattern can be broken out into two main sections including a constructor section and a prototype section. Prototyping allows functions and properties to be associated with objects. However, instead of each object instance getting a copy of all functions/properties each time an object is created, only one set of functions/properties exists across all objects resulting in less memory consumption. In other words, functions and properties are defined once per prototype rather than once per object.

Let's see how it works.

Page 5: Javascript design patterns

How does it work?One imporatant point in structuring a JavaScript code is that use namespace in your code . In this example, it uses a namespace called myNameSpace (if it is already defined it uses it otherwise it creates a new). As you can see it has a constuctor section where the member is intitialized and prototype section where the public methods are defined. Then it creates a new instance of the Calculator and uses the functions defined in it. You can create N number of Calculator objects through out your code. As mentioned earlier it won't create duplicate of functions with each of the objects created, instead all objects share the same method definitions like in C# or other programming languages so it uses less memory. This pattern is used mainly to create JavaScript libraries. End user can use the existing functionalities or add new functionalities or modify existing ones through prototypes.

Page 6: Javascript design patterns

Old code New Code

What changed?

Page 7: Javascript design patterns

2. Module PatternIn JavaScript programing language, functions can be used as a Module. Sometimes, it is required to create a singleton object instead of creating instance of a class. Inside the module, the inner functions do have the static scope with the other defined variables and functions.

Maximum applications written in JavaScript languages are singletons only. Hence, they all are written in Module pattern.

A Module can be considered as a Singleton Class in C#. In a Module, all the variables defined are visible only in the module. Methods in a module have scope and access to the shared private data and private methods. Hence, these methods are also called as Privileged methods.

Therefore, by creating one anonymous function returns a set of privileged methods in a simple object literal format. And because of the closure principle, those privileged methods have access to the inner methods and variables of the anonymous function. We call it as a Module Pattern.

Privileged MethodIn Module Pattern, you can write your private methods, private variables those you don’t want to expose to the other world and at the same time you will be able to write public and privileged methods also. The great usefulness of this pattern is that you can very well access your private methods and variables from your methods those are called as Privileged Methods.

ClosureIn order to learn Module Pattern, one must be aware of Closure principle. By using closure only modular pattern becomes very useful and powerful. Closure principle says that any inner function inside a parent function has scope to the other inner function and variables although after the parent function has returned. In Module Pattern, Privileged methods have scope to the other private variables and methods of the module.

Page 8: Javascript design patterns

How does it work?As you can see, there is no separate constructor section and method definition section like we have seen in Prototype pattern.

Like mentioned previously, calculator object is initialized through self execution of the method body. That is, an anonymous function is executed with 'eq' as parameter, and the result of the function (in this case, object literal after the return statement) is stored in the calculator object.

Very important thing to note about Module Pattern is that, Normally each time a new object is created a new set of functions will be created. In this case 5 objects will create 5 x 4 = 20 method definitions!. So it's not friendly on memory usage. So, that is the reason this pattern has a self executing method definition like given in the example which in turn implements the Singleton concept.

Page 9: Javascript design patterns

What changed?Old Code New Code

Page 10: Javascript design patterns

3. Revealing Module Pattern

Module Pattern and Revealing Module Pattern are conceptually same, but differs in the way member functions are defined.

Page 11: Javascript design patterns

How does it work?

As you can see, how methods are defined differs from Module Pattern. Method definitions are given names through var and the these variables are used in the return statement rather than function definitions like we have seen in Module Pattern. One advantage of using Revealing Module Pattern over Module Pattern is that we can have private methods. In this example 'add' method can be removed from the object literal in the return statement so that the object will expose only subtract, multiply and divide methods. But these 3 methods can

access 'add' method.

Page 12: Javascript design patterns

What changed?Old Code New Code

Page 13: Javascript design patterns

4. Revealing Prototype Pattern

Revealing Prototype Pattern is a combination of Prototype Pattern and Revealing Module Pattern.

Page 14: Javascript design patterns

How does it work?

Page 15: Javascript design patterns

What are the other benefits?

We have done the POC for patientfinancial.js and it works like charm.

Let’s all follow this pattern for better eco system.

What next?

Code will be unit testable(framework like jasmine etc can be adoptable)

Code will be reusable

Clean html and js separation of concern

Page 16: Javascript design patterns

Reference:

Book – “JavaScript: The Good Parts” – Douglas Crockford

http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript

http://peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in-javascript-tm

http://blog.alexanderdickson.com/javascript-revealing-module-pattern

And

Framework that follow the patterns are a lot, few are here.knockoutJSAngularJSBackbone.JSEmber.JSMany in github…