Avoid function redefinition using prototype

February 6th, 2013 § 1 comment § permalink

The problem of function redefinition

Here is the simple javascript constructor pattern,  in the first look it looks good and of-course it works fine.

function Person(name, school, college){
	this.name = name;
	this.school = school;
	this.college = college;

	this.toString = function(){
		return this.name + " attended " + this.school + " and " + this.college;
	};
}

var first = new Person("Revath", "st. Joseph's BHSS", "NTTF");
var second = new Person("S Kumar", "Model HSS", "Nettur");
console.log(first.toString());
console.log(second.toString());


The issue in this piece of code is toString() method. The toString() will be redefined for each new objects. Ideally every method should be shared by every instance of Person.

The solution using prototype

Here is the simple work around to get rid of this.

function Person(name, school, college){
	this.name = name;
	this.school = school;
	this.college = college;
}

Person.prototype.toString = function(){		
	return this.name + " attended " + this.school + " and " + this.college;
};

var first = new Person("Revath", "st. Joseph's BHSS", "NTTF");
var second = new Person("S Kumar", "Model HSS", "Nettur");
console.log(first.toString());
console.log(second.toString());


This prototype method will save memory since it uses the same object of toString method with all the instances of Person.  Using `this` results each instance having independent copy of function toString.