Constructor Pattern

Constructors is one of the first things that any IT school student learns when it comes to object oriented programming. I’m not gonna go much in to the basic concept of constructors. Just that knowing constructors is a method which initializes an instance of a class, after memory is being allocated to it, is enough. Every object oriented programming language has a variation of it, it may be hidden and be called beneath the top layer of execution, but it needs to be there, so is in Javascript.

In Javascript almost Everything is an object. So as it goes there are 3 ways to create objects in JS :

  1.  var newObject = {};
  2.  var newObject = Object.create( Object.prototype ); 
  3.  var newObject = new Object();

Note : if we pass a value to Object() constructor, it will create a new object wrapping the value passed. Otherwise it returns just an empty object.

So this creates the object newObject. I guess the most popular method is the first option because of its compactness.

There are several ways to define properties for this object too. I know, there are MANY ways to do one thing in JS, part of the complexity that comes with it.

  1. Using the dot syntax :
    • newObject.prop = "some value";
    • We can get the value back the same way, the usual dot syntax.
  2. Square bracket syntax. I’d like to call this the map syntax.
    • newObject["key"] = "some value";
    • Notice that the key has to be a string. Think of it as a map with string values as key and ANYTHING as value.
    • value can be returned with newObject["key"]
  3. Object.defineProperties :
        This is a kind of a hardcore method if you ask me. This method is only ECMAscript 5 compatible.

    Eg:

    Object.defineProperty( newObject, "someKey", {
        value: "for more control of the property's behavior",
        writable: true,
        enumerable: true,
        configurable: true
    });
    • One advantage we have by using this method compared to the two above is that we have more control over the behavior of the property.  A method defined with the Object higher class it self. We can configure the property as it is writable, enumerable and configurable.
      1. Writable : Object property can be assigned values using the assignment operator. Default is true obviously.
      2. Configurable : the property descriptor type can be changed. And the property can be deleted. Defaults to false.
      3. Enumerable : If true this property will show up when we enumerate the object properties, for example, by going through the object properties in a loop, or going through the Object.keys. Defaults to false.
    • There’s a lot of information from the Mozilla Developer network on this method, as is the case with any Javascript base knowledge. Thank you MDN!
      • Object properties, or as they call it property descriptors are either data descriptors or access descriptors. Those descriptors are themselves objects and they have the keys : ‘configurable’, and ‘enumerable’. Data descriptors, which are the ones with values, has the optional ‘writable’ key. Data descriptors also has the optional key ‘value’, which defaults to undefined… That’s the basic foundation of the value undefined errors we see as JS noobs. Access descriptors also has the optional keys, get and set. These are basically functions to get and set the property. Both get and set also defaults to undefined. I haven’t really seen them in use. But that could be just me.
      • As you can see there are other levels below this book of design patterns, which I will consider as out of the scope for these articles. If you want more on the method, please go the linked MDN article.
  4. There’s also the Object.defineProperties() method
    Object.defineProperties( newObject, {

      "someKey": {
        value: "Hello World",
        writable: true
      },
      "anotherKey": {
        value: "Foo bar",
        writable: false
      }
     });

How do we do inheritance by these methods? So we discussed about the new Object() constructor right? We can create any object which has the properties of the parent object by using the Object constructor. :

var individual = new Object(person);

individual has all the properties of the person. We can define new properties to individual using the Object defineProperty or defineProperties methods.

So we have used the Object construct like a class right. We defined new objects using new Object and so on. Like that we can define our own sort of classes. In JS this exists somewhere :

function Object () {
...
};

so we can use that with the new keyword to create instances of the Object. Like that we can create our own classes. Here the this keyword refers to the new object being created with the function.

function Car (model, year , miles) {
this.model = model;
this.year  = year;
this.miles = miles;
this.toString = function() {
return this.model + " has done " + this.miles + " miles";

};
};

Here we defined a basic constructor to the class Car. So we can create new Car object by using the new keyword :

var superCar = new Car('Porsche', 2011, 1500);
console.log(superCar.toString());

That is as basic a constructor can get in JS. But it’s not perfect. In Java or C++ do we define the functions inside our constructors?  Whenever we are calling the constructor above, it redefines the functions inside it. We would like to have the function defined once and able to be shared in all the instances like in other programming languages right?  Here comes ‘prototype’ to the rescue.

Every function in JS has a prototype object. This prototype object and its properties are shared between all instances that we create using new keyword. So instead of having a function defined in the function Car as above we can do this :

Car.prototype.toString = function() {
return this.model + " has done " + this.miles + " miles";

};

So that this toString method will be the one called by all instances of Car, instead of having their own separate toString methods. Just what we want.

That’s all we look in to with the Constructor pattern in JS. This hopefully covers how objects are able to be created in JS. Let’s move onto other interesting patterns in coming articles.

SUMMARY :

  • Contructors play an important role in Object Oriented language. The constructor pattern in JS explains how we can have basic constructors in Javascript.
  • There are multiple ways to create an object in Javascript, since everything in JS is Objects.
  • There are several ways to define properties for objects too.
  • defineProperties() is an effective ECMAscript 5 compatible way to define and customize properties the way we want.
  • By using the new keyword we can inherit properties to other objects.
  • We can define ‘classes’ by using the function keyword, and instantiate those ‘classes’ using the new keyword.
  • Every function has a ‘prototype’ object. We can use that to create shared functions of all instances of that function class.
Advertisements
This entry was posted in Design Patterns, Javascript and tagged , , , , , . Bookmark the permalink.

2 Responses to Constructor Pattern

  1. Good stuff. Reminds me of Addy Osmani’s book on design patterns.
    Ref: http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s