JavaScript Classes are templates for JavaScript Objects.
Always add a method named constructor():
Syntax
...
Example
...
The example above creates a class named "Car".
The class has two initial properties: "name" and "year".
Example
...
The example above uses the Car class to create two Car objects.
- * It has to have the exact name "constructor"
- * It is executed automatically when a new object is created
- * It is used to initialize object properties
Use the keyword class to create a class.
Always add a constructor() method.
Then add any number of methods.
Syntax
...
Create a Class method named "age", that returns the Car age:
Example
...
You can send parameters to Class methods:
Example
...
You will get an error if you do not follow the "strict mode" rules.
Example
In "strict mode" you will get an error if you use a variable without declaring it:
...
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:
...
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 gets access to the parent's properties and methods.
It can be smart to use getters and setters for your properties, especially if you want to do something special with the value before returning them, or before you set them.
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:
...
The name of the getter/setter method cannot be the same as the name of the property, in this case carname.
Many programmers use an underscore character _ before the property name to separate the getter/setter from the actual property:
Example
You can use the underscore character to separate the getter/setter from the actual property:
...
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":
...
That means that you must declare a class before you can use it:
Example
...
You cannot call a static method on an object, only on an object class.
Example
...
If you want to use the myCar object inside the static method, you can send it as a parameter:
Example
...
- * All the documentation in this page is taken from W3Schools
- * All the documentation in this page is created by Nantungga Putra