This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
Create a class named "Model" which will inherit the methods from the "Car" class:
class Car { constructor(brand) { this.carname = brand; } present() { return 'I have a ' + this.carname; } } class Model extends Car { constructor(brand, mod) { super(brand); this.model = mod; } show() { return this.present() + ', it is a ' + this.model; } } let myCar = new Model("Ford", "Mustang"); document.getElementById("demo").innerHTML = myCar.show();
Create a getter and a setter for the "carname" property:
class Car { constructor(brand) { this.carname = brand; } get cnam() { return this.carname; } set cnam(x) { this.carname = x; } } let myCar = new Car("Ford"); document.getElementById("demo").innerHTML = myCar.cnam;
You can use the underscore character to separate the getter/setter from the actual property:
class Car { constructor(brand) { this._carname = brand; } get carname() { return this._carname; } set carname(x) { this._carname = x; } } let myCar = new Car("Ford"); document.getElementById("demo").innerHTML = myCar.carname;
To use a setter, use the same syntax as when you set a property value, without parentheses:
Use a setter to change the carname to "Volvo":
class Car { constructor(brand) { this._carname = brand; } get carname() { return this._carname; } set carname(x) { this._carname = x; } } let myCar = new Car("Ford"); myCar.carname = "Volvo"; document.getElementById("demo").innerHTML = myCar.carname;
//You cannot use the class yet. //myCar = new Car("Ford") //This would raise an error. class Car { constructor(brand) { this.carname = brand; } } //Now you can use the class: let myCar = new Car("Ford")
Note: For other declarations, like functions, you will NOT get an error when you try to use it before it is declared, because the default behavior of JavaScript declarations are hoisting (moving the declaration to the top).
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