JavaScript 101: Object Oriented JS with Constructors

Till now we were only creating what are called as object literals by supplying key/value pairs. However this is not scalable and practical when we want to create 100's of objects and make sure they all have same members. This is where JS constructors come in.

What are Constructors?
Code wise, constructors are nothing but functions - they take in parameters, and have a body. However this is where the similarities end. Let's see a sample constructor:

function Dog(name, age, barkFun) {
    this.name = name;
    this.age = age;
    this.barkFunction = barkFun;
}


So this looks like a normal function, but what is this doing here?  Let us see how a constructor is invoked to know more -
var tito = new Dog("tito", 3, titoBark);

 Here, tito now stores the reference to the new object. How does this all work? It's all a combined effort of the new keyword and the constructor.

1. When new keyword is encountered, a new blank object is created.
2. Then, the constructor is invoked. The new keyword sets the reference of this to point to the newly created object.
3. The constructor body uses the this reference to set the object's properties.
4. Last, the newly created object is returned from the constructor function automatically (by the new keyword) and is assigned to the reference variable, tito.

Using object literals as parameters
Here we will see a use-case for object literals, which is not so suitable for constructors. Suppose we have a function, createHouse.

createHouse = function(numFloors, outsideColor, insideColor, numRooms, windowType)

As you can see, it will be very error prone, remembering argument's position every time while calling the method. One very innovative way to avoid this is to pass all the objects as an object literal:

var createHouseParams = {
    numFloors: 3, 
    outsideColor: "red",
    numRooms: 5, 
    windowType: "black"
};

.. and then send this object to the method:
createHouse(createHouseParams);

And, then the function/constructor can access any argument by its' name, no matter what order they are in. Smart!

Checking whether an object is an instance of some constructor
Say we have got a random object, and we want to make sure it's a Dog or some other object. We can use the instance of operator, to determine the same.
obj instance of Dog;

will return true, if obj was created by Dog constructor, else false.

Objects can add/remove properties later
Yes! Even after you use a constructor to create an object, you can still add properties by simply defining them and also delete properties by using delete operator. Even if you delete all the original properties, instance of operator will still report that the object belongs to the specific constructor! Weird.

No comments:

Post a Comment