➥ JS Tutorial
- JS HOME
- JS introduction
- JS Where to
- JS Output
- JS Statements
- JS Syntax
- JS Variables
- JS Operators
- JS Assignment
- JS Data Types
- JS Functions
- JS Objects
- JS Events
- JS Sting methods
- JS String Search
- JS Arrays Methods
- JS Arrays
- JS Sorting Arrays
- JS Array Iteration
- JS Math Object
- JS Comparison & Logical Operators
- JS if else and else if
- JS Switch Statement
- JS For Loop
- JS For In
- JS For Of
- JS While Loop
- JavaScript Break
- JS Sets
- JavaScript typeof
- JS Type Conversion
- JS Bitwise Operations
- JS JSON
- JS Best Practices
- JS Reserved Words
- JS Number Methods
➥ JS Objects
➥ JS Functions
➥ JS Classes
➥ JS HTML DOM
- JavaScript HTML DOM
- JS HTML DOM Document
- JS HTML DOM Elements
- Changing HTML
- JS Forms
- JS HTML DOM - CSS
- DOM Events
- HTML DOM Event Listener
➥ JS Browser BOM
➥ JS Web APIs
➥ JS AJAX
➥ JS JSON
Tutorial
JavaScript Classes
JavaScript Classes are templates for JavaScript Objects.
JavaScript Class Syntax
Use the keyword class
to create a class.
Always add a method named constructor()
:
Syntax:
class ClassName {
constructor() { ... }
}
Example:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The example above creates a class named "Car".
The class has two initial properties: "name" and "year".
A JavaScript class is not an object.
It is a template for JavaScript objects.
Using a Class
When you have a class, you can use the class to create objects:
The example below uses the Car class to create two Car objects.
The constructor method is called automatically when a new object is created.
EXAMPLE ❯
The Constructor Method
The constructor method is a special method:
• 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
If you do not define a constructor method, JavaScript will add an empty constructor method.
Class Methods
Class methods are created with the same syntax as object methods.
Use the keyword class
to create a class.
Always add a constructor()
method.
Then add any number of methods.
Syntax:
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
You can send parameters to Class methods: