Monday, September 1, 2014

Providers that make your life easy (Part II)

Chapter – VI
Providers that make your life easy (Part II)

Okay, in the previous post I've shown you how to create an object using JavaScript factory functions. So far so good. Now let me show you another way of creating an object in JavaScript. This work around includes creating an object using constructor functions. Following this pattern you would create an object like below,

var Actor = function (firstName, lastName, catchPhrase) {
                this.firstName = firstName;
                this.lastName = lastName;
                this.catchPhrase = catchPhrase;
                this.sayCatchPhrase = function() {
                    return this.firstName + " " + this.lastName + " says " + this.catchPhrase;
                };
            }

var clint = new Actor("Client", "Eastwood", "Go ahead. Make my day");

Except for some minor changes everything is almost same as before. As you can see when we create an object using the constructor function we always keep the variable’s [variable to which the constructor function holds its reference] first letter capitalized. Also we have used this. and then the property name of the object. Rather than using a colon (:) to assign a property value to one of the passed in parameter, here we simply assign it using an equal (=) sign. Last but not the least we called that constructor function by creating a new instance of it [see the new keyword at the start of the constructor function call]. Now if we write

clint.sayCatchPhrase();

The output is same as before

"Clint Eastwood says Go ahead. Make my day”

So what is the main difference between these two patterns for creating a JavaScript object? If we create an object with constructor function, the object is born with a type. Means our clint is an Actor type. You can check it in browser’s developer console by simply writing

clint instanceof Actor

Which will return true. But creating an object with a factory function doesn't have a type. Also you would use the constructor function pattern when creating an object of a type is too frequent.


In my next post we will take a deep dive into the wonderful world of Angular.js providers. Till then stay tuned!

No comments:

Post a Comment