JavaScript Classes JAVASCRIPT
- JavaScript Introduction
- JavaScript Syntax
- JavaScript innerHTML
- JavaScript document.write()
- Javascript - window.alert()
- JavaScript - console.log()
- JavaScript Comments
- JavaScript Variables
- JavaScript Operators
- JavaScript Data Types
- JavaScript Functions
- JavaScript Objects
- JavaScript Events
- JavaScript Strings
- JavaScript String Methods
- JavaScript Numbers
- JavaScript Number Methods
- JavaScript Arrays
- JavaScript Array Methods
- JavaScript Sorting Arrays
- JavaScript Array Iteration
- JavaScript Date Objects
- JavaScript Date Formats
- JavaScript Get Date Methods
- JavaScript Set Date Methods
- JavaScript Math Object
- JavaScript Conditions
- JavaScript Switch
- JavaScript Loop For
- JavaScript While Loop
- JavaScript Break and Continue
- JavaScript Type Conversion
- JavaScript Errors
- JavaScript Scope
- JavaScript this Keyword
- JavaScript Classes
- JavaScript Debugging
- JavaScript - Changing CSS
- JavaScript JSON
JavaScript Classes
Class Definition
Use the keyword class
to create a class, and always add the constructor()
method.
Methods
The constructor method is special, it is where you initialize properties, it is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.
Example
class Car {
constructor(brand) {
this.carname = brand;
}
present(x) {
return x + ", I have a " + this.carname;
}
}
mycar = new Car("Ford");
document.getElementById("demo").innerHTML = mycar.present("Hello");
Static Methods
Static methods are defined on the class itself, and not on the prototype.
That means you cannot call a static method on the object (mycar), but on the class (Car):
Example
class Car {
constructor(brand) {
this.carname = brand;
}
static hello(x) {
return "Hello " + x.carname;
}
}
mycar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(mycar);
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;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
The super()
method refers to the parent class.
By calling the super()
method in the constructor method, we call the parent's constructor method and get access to the parent's properties and methods.