JavaScript Classes are templates for JavaScript Objects.
Always add a method named constructor():
class ClassName { constructor() { ... } }
Example
class Car { constructor(name, year) { this.name = name; this.year = year; } }
The example above creates a class named "Car".
The class has two initial properties: "name" and "year".
A JavaScript class is not an object.
It is a template for JavaScript objects.
Example
let myCar1 = new Car("Ford", 2014); let myCar2 = new Car("Audi", 2019);
The example above uses the Car class to create two Car objects.
The constructor method is called automatically when a new object is created.
class ClassName { constructor() { ... } method_1() { ... } method_2() { ... } method_3() { ... } }
class Car { constructor(name, year) { this.name = name; this.year = year; } age() { let date = new Date(); return date.getFullYear() - this.year; } } let myCar = new Car("Ford", 2014); document.getElementById("demo").innerHTML = "My car is " + myCar.age() + " years old.";
class Car { constructor(name, year) { this.name = name; this.year = year; } age(x) { return x - this.year; } } let date = new Date(); let year = date.getFullYear(); let myCar = new Car("Ford", 2014); document.getElementById("demo").innerHTML= "My car is " + myCar.age(year) + " years old.";
Chrome 49 | Edge 12 | Firefox 45 | Safari 9 | Opera 36 |
Mar, 2016 | Jul, 2015 | Mar, 2016 | Oct, 2015 | Mar, 2016 |
class Car { constructor(name, year) { this.name = name; this.year = year; } age() { // date = new Date(); // This will not work let date = new Date(); // This will work return date.getFullYear() - this.year; } }Learn more about "strict mode" in: JS Strict Mode.