JavaScript | The Constructor Pattern

There are 3 ways to create object in javascript

var obj = new Object();

var obj = Object.Create(Object.prototype);

var obj = {};


Javascript ES5 dosent support the concept called class. It supports only the contructor function, means Instance can be created on the functions. This is called constructor pattern

function Car( model, year, miles ) {
 
  this.model = model;
  this.year = year;
  this.miles = miles;
 
  this.toString = function () {
    return this.model + " has done " + this.miles + " miles";
  };
}
 
// Usage:
 
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
 
// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log( civic.toString() );
console.log( mondeo.toString() );

No comments

Powered by Blogger.