ES6 | Class Variable Alternatives
A class is created using a class keyword. Whenever an object is initialized, the class method gets called for the object. The following examples show the class variable alternatives:
Using Class: The class keyword allows user to create a class. A class keyword is essential for the creation of a class in JavaScript.
- Program:
<!DOCTYPE html><html><head><h1>GeeksforGeeks</h1></head><body><p id="gfg"></p><script>class Fruit {constructor(fname) {this.fruit1 = fname;}}Fru =newFruit("Mango");document.getElementById("gfg").innerHTML= Fru.fruit1;</script></body></html> - Output:

Using Methods: Every time the instance of a class is created. It is initialized using the constructor() method. If the user has not defined the constructor() method, then JavaScript does it automatically.
- Program:
<!DOCTYPE html><html><head><h1>GeeksforGeeks</h1></head><body><p id="gfg"></p><p id="gfg1"></p><script>class Fruit {constructor(fname) {this.fruit1 = fname;}present() {return"My favourite fruit is "+this.fruit1;}}Fru =newFruit("Mango");document.getElementById("gfg").innerHTML= Fru.fruit1;document.getElementById("gfg1").innerHTML= Fru.present();</script></body></html> - Output:

Using Static Method: This methods is simple and they are called on the class and not on the objects of the class.
- Program:
<!DOCTYPE html><html><head><h1>GeeksforGeeks</h1></head><body><p id="gfg1"></p><script>class Fruit {constructor(fname) {this.fruit1 = fname;}staticnew() {return"Mango!!!!";}}Fru =newFruit("Mango");document.getElementById("gfg1").innerHTML= Fruit.new();</script></body></html> - Output:

Using Inheritance: Inheritance allows the child class to inherit the properties of the parent class. The keyword “extends” is used for this purpose.
- Program:
<!DOCTYPE html><html><head><h1>GeeksforGeeks</h1></head><body><p id="gfg1"></p><script>class Fruit {constructor(fname) {this.fruit1 = fname;}present() {return"My favourite fruit is "+this.fruit1;}}class Healthy extends Fruit {constructor(fname, mod) {super(fname);this.healthy = mod;}show() {returnthis.present() +', it is very '+this.healthy;}}fru =newHealthy("Mango","healthy");document.getElementById("gfg1").innerHTML= fru.show();</script></body></html> - Output:

Using Get- Set Method: Getters allows to get the values of ES6 class variables and Setters allows to set those values respectively in proper fields.
- Program:
<!DOCTYPE html><html><head><h1>GeeksforGeeks</h1></head><body><p id="gfg1"></p><script>class Fruit {constructor(fname) {this.fruit1 = fname;}get fruitss() {returnthis.fruit1;}set fruitss(x) {this.fruit1 = x;}}Fru =newFruit("Mango");document.getElementById("gfg1").innerHTML= Fru.fruitss;</script></body></html> - Output:

Supported Browsers: The browsers supported by ES6 Class Variable Alternative are listed below:
- Google Chrome 49
- Firefox 45
- Internet Explorer Edge 12
- Opera 36
- Safari 9


