This content originally appeared on CodeSource.io and was authored by Deven
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.
The post Creating a Reusable Class in JavasScript appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-02-10T15:15:59+00:00) Creating a Reusable Class in JavasScript. Retrieved from https://www.scien.cx/2021/02/10/creating-a-reusable-class-in-javasscript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.