javascript

Creating a Reusable Class in JavasScript


In this article, you will learn to create a Reusable Class in Javascript. In Javascript Class is the template for creating objects. we can define a class is using a class declaration and To declare a class, we use the class keyword with the name of the class.

Consider the example below to to create a Reusable Class in JavasScript.

class Fruit {
  constructor(sweetFruit, sourFruit) {
    this.sweetFruit = sweetFruit;
    this.sourFruit = sourFruit;
  }
}

const newFruit = new Fruit('mango', 'pineapple');
console.log(newFruit.sweetFruit);  // 'mango'

In the code snippet above we used the class keyword, and gave a name to our class. Inside that we added a constructor function that initializes our object.

Consider the another example below:

class Fruit {
  constructor(sweetFruit, sourFruit, nutFruit) {
    this.sweetFruit = sweetFruit;
    this.sourFruit = sourFruit;
		this.nutFruit = nutFruit;
  }

	// This is a method
	swapFruits() {
		[this.sweetFruit, this.sourFruit] = [this.sourFruit, this.sweetFruit];
	}
}

// Test the Fruit class
const newFruit = new Fruit('Mango', 'pineapple', 'oak');
newFruit.swapFruits();
console.log(newFruit.sweetFruit); 

In the code snippet above, the Fruit class is a simple package that bundles together two public fields sweetFruit and SourFruit and it’s also very easy to add methods to our class.


Share on social media

//