فئات javascript
فئات javascript
Class Inheritance
To create a class inheritance, use the extends keyword.
A class created with a class inheritance inherits all the methods from
another class:
Example
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;
}
}
To add getters and setters in the class, use the get and set keywords.
Example
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;
}
}
document.getElementById("demo").innerHTML = myCar.cnam;
Note: even if the getter is a method, you do not use parentheses
when you want to get the property value.
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
set carname(x) {
this._carname = x;
}
}
document.getElementById("demo").innerHTML = myCar.carname;
To use a setter, use the same syntax as when you set a property
value, without parentheses:
Example
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;
}
}
That means that you must declare a class before you can use it:
Example
//You cannot use the class yet.
//myCar = new Car("Ford")
//This would raise an error.
class Car {
constructor(brand) {
this.carname = brand;
}
}
Example
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
If you want to use the myCar object inside the static method, you
can send it as a parameter:
Example
class Car {
constructor(name) {
this.name = name;
}
static hello(x) {
return "Hello " + x.name;
}
}
let myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);
Email : [email protected]
SOUHAIL DEVELOPER
Souhail Laghchim | Developer & Designer
Email : [email protected]
WebSite : https://souhail-laghchim-pro.blogspot.com/