Constructor in JavaScript

A constructor is a function used as a prototype for an object, and when called, create a new object instance from the prototype.

function constructorName(passedParameters) {
    //set properties and run methods needed on object creation
    this.property1 = property1; //this keyword used to reference object

//adding a new property to a prototype
constructorName.prototype.newProperty = newPropertyValue;
var newObject = new constructorName(passedParams);


The 'new' keyword is used to create a new object from a function.

function carConstructor(wheels, make){
    this.wheels = wheels;
    this.make = make;
carConstructor.prototype.mirrors = 3;
var newCar = new carConstructor(4, 'Mercedes');

< Create Object using Constructor   |   Console Output >

© 2019 SyntaxDB. All Rights Reserved.