React Tutorials
React ES6
React Hooks
ES6 introduces classes.
A class is a type of activity, but instead of using a keyword function
to start it, we use a keyword class
, and properties are provided within the constructor()
method.
A simple class constructor:
class Car {
constructor(name) {
this.brand = name;
}
}
Note: the class name status. We have started the word, "Car", in capital letters. This is a general rule for naming classes.
You can now create items using the Car category:
Create an object called "mycar" based on the Car class:
class Car {
constructor(name) {
this.brand = name;
}
}
const mycar = new Car("Ford");
Note: The builder function is automatically called when the item is launched.
You can add your methods to the class:
Create a method named "present":
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
const mycar = new Car("Ford");
mycar.present();
As you can see in the example above, you call the path by referring to the name of the object path followed by parentheses (parameters that will fit inside parentheses).
To create a classroom asset, use an extends
keyword.
A class built with a legacy class benefits all the ways from another category:
Create a class named "Model" which will inherit the methods from the "Car" class:
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
class Model extends Car {
constructor(name, mod) {
super(name);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model
}
}
const mycar = new Model("Ford", "Mustang");
mycar.show();
The super()
method refers to the parent class.
By calling the super()
method the builder path, we call the parent builder path and gain access to the parent property and methods.