Class in JavaScript
- In JavaScript Class is a blueprint for creating objects.
- The concept of classes is introduced to javascript with ECMAScript 6 (ES6), which provides a more structured and syntactic way to create objects and define their properties and methods.
The class consist of two components:
- Declarations
- Expressions
Declarations:
- To declare a class in javascript class keyword is used for any particular name according to naming conventions in javascript.
- Class names should always start with uppercase.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
//Declaring class
class Employee {
//Initializing an object
constructor(id, name) {
this.id = id;
this.name = name;
}
//Declaring method
detail() {
document.writeln(this.id + " " + this.name + "<br>")
}
}
//passing object to a variable
var e1 = new Employee(101, "Martin");
var e2 = new Employee(102, "Duke");
e1.detail(); //calling method
e2.detail();
</script>
</body>
</html>
Output:
101 Martin
102 Duke
Class Expressions:
- We can define a class in javascript by using class expression, here it is not mandatory to name the class,
- The class expressions can be named or unnamed.
Unnamed class expression:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var emp = class {
constructor(id, name) {
this.id = id;
this.name = name;
}
};
document.writeln(emp.name);
</script>
</body>
</html>
Output:
emp
Named Expression:
- we can express the particular name for a class, here scope of the class name is up to the class body, the class is accessed by using the class name property.
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var emp = class Employee {
constructor(id, name) {
this.id = id;
this.name = name;
}
};
document.writeln(emp.name);
/*document.writeln(Employee.name);
Error occurs on console:
"ReferenceError: Employee is not defined
*/
</script>
</body>
</html>
Output:
Employee