JS Class Expression
JavaScript class is a type of function declared with a class keyword, that is used to implement an object-oriented paradigm. Constructors are used to initialize the attributes of a class.
There are 2 ways to create a class in JavaScript.
- Class Declaration
- Class Expression
In this article, we will discuss class expression to declare classes in JavaScript and how to use them.
Class Expression
The class expression is another way of creating classes in JavaScript and they can be named or unnamed. If named, the class name is used internally, but not outside of the class.
Syntax
- Using named class expression:
const variable_name = new Class_name {
// class body
}
- Using unnamed class expression:
const variable_name = class{
//class body
}
Example 1: Named class expression
const Website = class Geek {
constructor(name) {
this.name = name;
}
websiteName() {
return this.name;
}
};
const x = new Website("GeeksforGeeks");
console.log(x.websiteName());
Output
GeeksforGeeks
Example 2: Unnamed class expression.
const Website = class {
constructor(name) {
this.name = name;
}
returnName() {
return this.name;
}
};
console.log(new Website("GeeksforGeeks").returnName());
Output
GeeksforGeeks
Key Features of Class Expressions
- Anonymous Classes: Just like anonymous functions, you can define a class without giving it a name. This can be useful for situations where you donât need to reference the class elsewhere.
- Assigning Classes to Variables: You can assign a class to a variable, which allows you to instantiate objects from that class later. This is a common way of using class expressions.
- Self-Invoking Class Expressions: A class can be invoked immediately after it is created, which allows for the creation of new objects right away.
Supported Browser
- Chrome 42
- Edge 13
- Firefox 45
- Opera 29
- Safari 7