Javascript : constructor pattern

March 1st, 2013 § 0 comments § permalink

Its just a simple demo of constructor pattern on Javascript. In case if you didn’t noticed, in my last post I ready used constructor pattern with Object.create.

In Vanilla JS


function Person(name, school){
	this.name = name;
	this.school = school;
}
 
Person.prototype.toString = function(){
	console.log(this.name + " studied in " + this.school);
}
 
 
var me = new Person("Revath", "St. Joseph's BHSS");
me.toString();

I recommend, you should checkout why you should use prototype instead of this.

jsperf : prototype v/s this

In CoffeeScript


class Person
    constructor: (name, school) ->
        @name = name
        @school = school
        
    toString: ->
        console.log @name + " studied in " + @school
        
        
        
me = new Person("Revath", "St. Joseph's boys high school")
me.toString();