Constructors (Prototypes) in JavaScript

Constructor is nothing but the function from which we can create new objects. This constructor is also called as prototype.

Below example illustrates how to define the constructors in JavaScript.

function Car(name,price) {
         this.price = price;
         this.name = name;
}

// properties for above class can be created using prototype property
Car.prototype.model= “sportz”;

// Methods for above class can be created using prototype property
Car.prototype.calculateTax = function () {
         return this.price*0.12;
};

var car1 = new Car(“Audi A9”, 48888)
console.log(“Car1 price -> ” + car1.name + ” ” + car1.price)
console.log(“Car1 tax -> ” + car1.calculateTax())

var car2 = new Car(“Jeep”, 66666)
console.log(“Car2 price -> ” + car2.name + ” ” + car2.price)
console.log(“Car2 tax -> ” + car2.calculateTax())

You may also like...