Skip to content

JavaScript constructor prototype

  • by

In JavaScript, constructors and prototypes are used to create and define objects and their behaviors. The constructor function is used to create new instances of an object, and the prototype is used to add properties and methods to those instances.

Here’s the syntax:

// Constructor function
function ConstructorName(parameter1, parameter2, ...) {
  // Constructor logic
  this.property1 = value1;
  this.property2 = value2;
  // ...
}

// Adding properties to the prototype
ConstructorName.prototype.propertyName = value;

// Adding methods to the prototype
ConstructorName.prototype.methodName = function() {
  // Method logic
};

The JavaScript constructor prototype syntax involves defining a constructor function and then adding properties and methods to its prototype.

  1. Define the constructor function using the function keyword followed by the constructor name. It’s a convention to capitalize the constructor name to distinguish it from regular functions.
  2. Inside the constructor function, you can initialize object properties using the this keyword. Assign values to the properties based on the passed parameters or other logic.
  3. To add properties to the prototype, access the prototype property of the constructor function and assign properties to it. These properties will be shared by all instances of the object.
  4. To add methods to the prototype, use the same prototype property and assign a function to it. The function represents the method logic and can access the object’s properties using the this keyword.

Here’s an example using the syntax:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
};

JavaScript constructor prototype example

Simple example code of using the constructor and prototype pattern in JavaScript:

// Constructor function
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

// Adding a method to the prototype
Car.prototype.start = function() {
  console.log(`Starting the ${this.make} ${this.model}`);
};

// Creating instances of Car
const car1 = new Car("Toyota", "Camry", 2021);
const car2 = new Car("Honda", "Civic", 2022);

// Accessing properties
console.log(car1.make); 
console.log(car2.year);

// Calling a method
car1.start(); 
car2.start(); 

Output:

JavaScript constructor prototype

Do comment if you have any doubts or suggestions on this Js constructor topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading