30 May 2014

What's THIS? (In Javascript) - PART II

As promised, here it's the second part of the wondrous journey through the invocation patterns.

The Constructor invocation pattern
Javascript is a class-free prototypal inheritance language, this means that there are no classes and that objects can inherits properties directly from other objects. The syntax for the constructor invocation pattern is similar to the one found in the class-based languages but the mechanism behind that is quite different. An example:

// A Constructor function
var HouseConstructor = function(houseType, numberOfBathrooms, withGarden) {
    this.houseType = houseType;
    this.numberOfBathrooms = numberOfBathrooms;
    this.hasGarden = withGarden;

// A new object is created by using the Constructor invocation pattern
var newHouse = new HouseConstructor("Viareggina", 3, true);

// Let's extend the function's prototype with a new method
HouseConstructor.prototype.getHouseType = function() { return this.houseType; };

// The object gets the new method

In the example above a new constructor function is created and bound to a variable with a capitalised name (a convention for constructor functions), then a new object is created by using the new keyword followed by the invocation of the constructor function. After that, the constructor function object's prototype (in Javascript functions are objects) is extended by adding a new method, so all instances created by that constructor will have the new method, even the ones created before. This works because new objects are created with an hidden variable which points to the constructor function's prototype. When using the Constructor invocation pattern the "this" points to the newly created object.

The Apply invocation pattern

As said before in Javascript functions are objects and therefore can have methods. Among the out-of-the-box function's methods we find the apply method.
Using the apply invocation pattern we can execute a function by passing it the value of this and an array of parameters. An interesting use of this pattern is to run an object's method on another object which hasn't that method. Let's see this:

var aHouse = {
    houseType : "Villetta",
    getHouseType : function() { return this.houseType; }

 //This object has a houseType property but not a method to get it.
var aCar = {
    carType : "SuperCar",
    houseType : "Villa"   //Just for example :)

// Running aHouse's method on aCar object.
alert(aHouse.getHouseType.apply(aCar));  // = "Villa"

In the example we're running aHouse's method on aCar object by using the apply method and passing aCar object as the value of "this" for the apply function.
Well, this was the last Javascript invocation pattern, maybe more posts on these topics will follow, or maybe not :)