This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
class ClassName {
constructor() { ... }
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
When you have a class, you can use the class to create objects:
let myCar1 = new Car("Ford", 2014); let myCar2 = new Car("Audi", 2019);
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
}
Create a Class method named "age", that returns the Car age:
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.";
You can send parameters to Class methods:
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.";
The following table defines the first browser version with full support for Classes in JavaScript:
Chrome 49 | Edge 12 | Firefox 45 | Safari 9 | Opera 36 |
Mar, 2016 | Jul, 2015 | Mar, 2016 | Oct, 2015 | Mar, 2016 |
In "strict mode" you will get an error if you use a variable without declaring it:
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; } }
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon