JavaScript class Declaration
Example
Create a Car class, and then create an object called "mycar" based on the Car class:
class Car { // Create a class
constructor(brand) { // Constructor
this.carname = brand;
// Class body
}
}
mycar = new Car("Ford"); // Create an object of Car
class
Definition and Usage
A class
is a type of function, but instead of using the keyword
function
to initiate it, we use the keyword
class
, and the properties are assigned inside a
constructor()
method.
The constructor()
method is called each time the class object is initialized.
Note: Unlike functions, and other JavaScript declarations, class declarations are not hoisted (you must declare a class before you can use it).
Note: The syntax in classes must be written in "strict mode".
For more information about classes, read our JavaScript Classes Tutorial.
Browser Support
The following table defines the first browser version with full support for Classes in JavaScript:
Keyword | |||||
---|---|---|---|---|---|
class | 49.0 | 12.0 | 45.0 | 9.0 | 36.0 |
Syntax
class className {
// class body
}
Technical Details
JavaScript Version: | ECMAScript 2015 (ES6) |
---|
Related Pages
JavaScript Tutorial: JavaScript Classes
JavaScript Tutorial: JavaScript ES6 (EcmaScript 2015)
JavaScript Tutorial: JavaScript this
JavaScript Tutorial: JavaScript Strict Mode