JavaScript Constructors and Prototypes

JavaScript lack classes, it turns to constructors and prototype to bring a similar order to objects.

Constructors

A constructor is simply a function that is used with new to create an object. There are built-in constructors for Object, Array and Functions. The advantage of constructors is that objects created with the same constructor contains the same properties and methods.

The constructor names should begin with capital letter, to distinguish them from other functions.

function Person() {
    //intentionally empty
}

This function is a constructor. The clue that Person is a constructor is in the name – the first letter is capitalized. Let’s create some instances;

var person1 = new Person();
var person2 = new Person();

The new operator automatically creates an object of the given type and returns it. We can use the instanceof operator to confirm object’s type.

console.log(person1 instanceof Person)		//returns true
console.log(person2 instanceof Person)		//returns true

We can also check the type of an instance using the constructor property. For generic objects (those created via an object literal or the object constructor), constructor is set to Object. For objects created with a custom constructor, constructor points back to that constructor function, in our case Person.

console.log(person1.constructor === Person);	//returns true
console.log(person2.constructor === Person);	//returns true

Let’s add some properties inside constructor;

function Person(name){
    this.name = name;
    this.sayName = function()
    {
        console.log(this.name);
    };
}

Now we can use the Person constructor to create objects with an initialized name property;

var person1 = new Person("shahzad");
var person2 = new Person("ali");
console.log(person1.name);		//returns shahzad
console.log(person2.name);		//returns ali

person1.sayName();			//returns shahzad
person2.sayName();			//returns ali

Make sure to always call constructors with new; otherwise it will be created on global objects. Constructors don’t eliminate code redundancy. For example, each instance has its own sayName() method even though sayName() doesn’t change. What if we have 100 instances of an object, then there are 100 copies of a function that do the exact same thing, just with different data.

If would be much more efficient if all of the instances shared one method, and then that method could use this.name to retrieve the appropriate data. This is where prototypes come in.

Prototypes

Think of prototype as a recipe for an object. Almost every function (except some built-in functions) has a prototype property that is used during the creation of new instances. This property is shared among all of the object instances. For example, hasOwnProperty() method is defined on generic Object prototype, but it can be accessed from any objects.

function Person(name){
    this.name = name;
}

Person.prototype.sayName = function() {
    console.log(this.name);
};

var p = new Person("shahzad");
var p1 = new Person("ali");

console.log(person1.name)	//returns "shahzad"
console.log(person2.name)	//returns "ali"
person1.sayName();		//returns “shahzad”
person2.sayName();		//returns “ali”

Let’s assign constructor property specifically on the prototype;

Person.prototype = {
    constructor: Person,
    
    sayName: function() {
        console.log(this.name);
    },
    
    toString: function() {
        return "[Person " + this.name + "]";
    }
};

var person1 = new Person("shahzad");
var person2 = new Person("ali");
console.log(person1 instanceof Person);		//returns true
console.log(person1.constructor === Person);	//returns true
console.log(person1.constructor === Object);	//returns false
console.log(person2 instanceof Person);		//returns true
console.log(person2.constructor === Person);	//returns true
console.log(person2.constructor === Object);	//returns false
FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect