Javascript Classes - Constructor, Super, Extends and Static (Reference)
In Javascript, classes are a new feature that allows you to define a class and its methods. Some of the features of classes are Constructor, Super, Extends, Static.
constructor
The constructor is a special method that is called when a new instance of a class is created.It is used to initialize the newly created object.
class obj_constr {
constructor(val) {
this.aaa = val;
}
}
var x = new obj_constr("aaa");
x.aaa;
// aaa
super
The super keyword is used to call the constructor of the parent class.
class obj_constr_1 {
constructor(val_1) {
this.aaa = val_1;
}
}
class obj_constr_2 extends obj_constr_1 {
constructor(val_1, val_2) {
super(val_1);
this.bbb = val_2;
}
}
var x = new obj_constr_2("aaa", "bbb");
x.aaa;
// aaa
extends
The extends keyword is used to inherit the properties and methods of another class.
class obj_constr_1 {
constructor(val_1) {
this.aaa = val_1;
}
TEST1() {
return this.aaa;
}
}
class obj_constr_2 extends obj_constr_1 {
constructor(val_1, val_2) {
super(val_1);
this.bbb = val_2;
}
TEST2() {
return this.TEST1();
}
}
var x = new obj_constr_2("aaa", "bbb");
x.TEST2();
// aaa
static
The static keyword is used to declare a static property. Static properties are properties that belong to the class instead of to instances of the class.
class obj_constr {
constructor(val) {
this.aaa = val;
}
static TEST() {
// Code
}
}
var x = new obj_constr("aaa");
obj_constr.TEST();
