How to create a class in JavaScript
In JavaScript classes can be created using functions. Let’s see how.
function Car() {
this.make = 'Honda';
this.model = 'Civic';
this.color = 'gray';
this.getInfo = function() {
return this.make + ' ' + this.model + ' ' + this.color;
};
}
var mycar = new Car();
The method getInfo() gets recreated every time we create a new object. Instead we can add getInfo() to the prototype.
Car.prototype.getInfo = function() {
return this.make + ' ' + this.model + ' ' + this.color;
}
Categories :
OOP
javascript