Basic JavaScript Constructor
Basic JavaScript Constructor
by Nirvanachain
HTML
<!-- Source:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
-->
JavaScript
/**
JavaScript doesn't support the concept of classes but it does support special constructor functions that work with objects. By simply prefixing a call to a constructor function with the keyword "new", we can tell JavaScript we would like the function to behave like a constructor and instantiate a new object with the members defined by that function.
Inside a constructor, the keyword this references the new object that's being created. Revisiting object creation, a basic constructor may look as follows:
**/
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() );