Wednesday, July 8, 2015

Javascript Mixing Pattern

In traditional object oriented languages we could write inherited classes and reuse functionality. However, in javascript, inheritance comes from chaining prototypes.  But for performance reason, you should not have long prototype chain. Therefore in javascript, for code reuse we can use mixing pattern. Multiple inheritance makes it easy by using mixing pattern.
The concept of mixing is to take an object and mixing the functionality with another object.
First we will define two objects.
Then we will define mixings.
Then we will define mixing function.
Now add mixing to the above objects and check the output.
Most important thing to remember is, you are injecting functionality to your code. Therefore you must document it properly in a large code base.

Javascript Inheritance Pattern

In javascript we do not have classes. We have objects. There's is only one way to make inheritance in javascript. That is by chaining prototype.
in the following example I have defined Person and Student objects where Student object inherit form the Person object.

Javascript Create Objects in Different ways.

Object Literals

In javascript we can create a object using object literals.
To store data we can define properties. In here I have showed four different ways to define properties.

Using Object.create

Another way to create objects in javascript is using Object.Create. Advantage is, it will allows to create objects which based upon other objects.
Now we will create objects which based on another object.
In above code, myBentleyCar's prototype is bentleyCar. We can verify that using following code.

Constructor functions

Another way to create objects in javascript is using constructor functions. In here name of the function should be begins with upper case letter, Then we can easily identify a constructor with other javascript functions. We can pass parameters using following way.
Then we define a method in this object. But reality is a property which contains a function object. But logically we could describe it as a method.
Using instanceof keyword we can determine whether an object is a instance of particular constructor.
The way we declare the method is not a proper way. Reason is there is a performance drawback in there. As I have mentioned that method is a new function object. So each time when we create a new object, this function object will be created.
And also it will give inheritance issues, if we define our methods in the constructor.
Instead of that, we can define methods in prototype. Any function that you define in the prototype will be shared across all the instances of that function.