ECMAScript 2015
ES6, also known as ECMAScript2015, introduced classes.
Class Definition
Use the keyword class
to create a class, and always add the constructor()
method.
The constructor method is called each time the class object is initialized.
Example A simple class definition for a class named "Car":
class Car { constructor(brand) { this.carname = brand; } }
Now you can create objects using the Car class:
<script> class Car { constructor(brand) { this.carname = brand; } } mycar = new Car("Ford"); document.getElementById("demo").innerHTML = mycar.carname; </script>
Methods
The constructor method is special, it is where you initialize properties, it is called automatically when a 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.
You are also free to make your own methods, the syntax should be familiar:
<script> class Car { constructor(brand) { this.carname = brand; } present() { return "I have a " + this.carname; } } mycar = new Car("Ford"); document.getElementById("demo").innerHTML = mycar.present(); </script>
As you can see in the example above, you call the method by referring to the object's method name followed by parentheses (any parameters would go inside the parentheses).
<script> class Car { constructor(brand) { this.carname = brand; } present(x) { return x + ", I have a " + this.carname; } } mycar = new Car("Ford"); document.getElementById("demo").innerHTML = mycar.present("Hello"); </script>
Complete Code For Defining Class In Java Script
<!DOCTYPE html> <html> <head> <title>Class In Java Script</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">Class In Java Script</h1> </div> <div class="well"> <h2 id="demo1"></h2> <h2 id="demo2"></h2> <h2 id="demo3"></h2> <script> class Car { constructor(brand) { this.carname = brand; } present() { return "I have a " + this.carname; } } mycar = new Car("Ford"); document.getElementById("demo1").innerHTML = mycar.carname; document.getElementById("demo2").innerHTML = mycar.present(); document.getElementById("demo3").innerHTML = mycar.present("Hello"); </script> </div> </div> </body> </html>