Information



Tags



Share

How to use JavaScript classes and methods in ES6

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

>

Share





Advertisement

Advertisement



Definition(*)

JavaScript classes are introduced by ES6, also known as ECMAScript2015.

A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties is assigned inside a constructor() method.

Use the keyword class to create a class, and always add a constructor method.

The constructor method is called each time the class object is initialized.

Note: You can create your own methods in JavaScript classes however the constructor method is special, it is where you initialize properties, it is called automatically when an class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.

Code

Define country names in the constructor of the country class.

Set revenue values for each country using a setter. To add getters and setters in the class, use the get and set keywords.

In the name method, return associated countries.

To create a class inheritance, use the extends keyword. In this way, the evaluate class inherits all the methods from the country class.

To access parent methods, properties, and variables, use the super() method in the constructor method as showed below.

You can call the static correlation method defined on the class itself without using the object to calculate the correlation between revenues.

Now, you can define new object properties and view results.



class country{
constructor(c_1, c_2, c_3){
this.country_1 = c_1;
this.country_2 = c_2;
this.country_3 = c_3;
}

set revenue(x){
this.country_1_revenue = x;
this.country_2_revenue = x;
this.country_3_revenue = x;
}

name(){
return "Associated Countries: " + this.country_1 + " / " + this.country_2 + " / " + this.country_3;
}

}

class evaluate extends country{
constructor(c_1, c_2, c_3){
super(c_1, c_2, c_3);
}

print(result_1, result_2, result_3){
return this.name() + " & Revenues (in order): " + this.country_1_revenue + " / " + this.country_2_revenue + " / " + this.country_3_revenue + " & Correlation (in order): " + result_1 + " / " + result_2 + " / " + result_3;
}

static correlation(x, y){
return x / y;
}

}

countries = new evaluate("England", "USA", "Italy");
countries.country_1_revenue = 500;
countries.country_2_revenue = 200;
countries.country_3_revenue = 1000;
document.getElementById("test").innerHTML = countries.print(evaluate.correlation(countries.country_1_revenue, countries.country_2_revenue), evaluate.correlation(countries.country_2_revenue, countries.country_3_revenue), evaluate.correlation(countries.country_1_revenue, countries.country_3_revenue));

Result:

References

(*) https://www.w3schools.com/js/js_classes.asp