javascript

Create a Custom Class in Javascript Using the Constructor Pattern


In this article, you will learn to create a Custom Class in Javascript Using the Constructor Pattern. Constructor Pattern can also help you understand how JavaScript classes really work.

Consider the following example to create a Custom Class in Javascript Using the Constructor Pattern.

function Fruit(sweetFruit, sourFruit) {
  // Store public data using 'this'
  this.sweetFruit = sweetFruit;
  this.sourFruit = sourFruit;

  // Add a nested function to represent a method
  this.swapFruits = function () {
    [this.sweetFruit, this.sourFruit] = [this.sourFruit, this.sweetFruit];
  };
}

// using a class with an identical constructor
const newFruit = new Fruit("mango", "pineapple");
console.log(newFruit.sweetFruit);

newFruit.swapFruits();
console.log(newFruit.sweetFruit);

In the code snippet above first, you write a constructor function that accepts parameters and initializes your object, and then you use the this keyword to create publicly accessible fields.


Share on social media

//