JavaScript Classes
Classes are templates for creating objects.
We use the class keyword to create a class, and the class body is inside a pair of curly braces.{}Inside, we can, within the curly braces,{}define the positions of class members, such as methods or constructors.
Each class contains a special method.constructor()It is the class's constructor. This method is used to create and initialize an object created byclassthe created object.
The syntax for creating a class is as follows:
Example:
Example
The above example creates a class named "Example".
The class initializes two properties: "name" and "url".
Browser Support
The numbers in the table indicate the first browser version that supports this feature.
| Chrome 49 | Edge 12 | Firefox 45 | Safari 9 | Opera 36 |
| Mar, 2016 | Jul, 2015 | Mar, 2016 | Oct, 2015 | Mar, 2016 |
Using Classes
After defining a class, we can use thenewkeyword to create objects:
Example
Try it Yourself »
When creating an object, the constructor method is automatically called.constructor()。
Class Expressions
Class expressions are another way to define a class. Class expressions can be named or unnamed. The name of a named class expression is local to the class body.
Example
Constructor Method
The constructor method is a special method:
- The constructor method is named constructor().
- The constructor method is automatically executed when creating a new object.
- The constructor method is used to initialize object properties.
- If you do not define a constructor method, JavaScript will automatically add an empty constructor method.
Class Methods
We use the keywordclassto create a class, and can add aconstructor()method, and then add any number of methods.
In the following example, we create an "age" method that returns the website's age:
Example
Try it Yourself »
We can also pass parameters to class methods:
Example
Try it Yourself »
Strict Mode "use strict"
The bodies of class declarations and class expressions are executed in strict mode. For example, constructors, static methods, prototype methods, getters, and setters are all executed in strict mode.
If you do not follow strict mode, an error will occur:
Example
Try it Yourself »
The following example uses an undeclared variable in a class:

For more on strict mode, you can refer to:JavaScript Strict Mode (use strict)
Reference
Class Methods
| Method | Description |
|---|---|
| constructor() | Constructor, used to create and initialize a class. |
Class Keywords
| Keyword | Description |
|---|---|
| extends | Inherit a class |
| static | Defines a static method in a class. |
| super | Calls the constructor method of the parent class. |