JavaScript Classes
Classes are one of the features introduced in the ES6 version of JavaScript.
A class is a blueprint for the object. You can create an object from the
class.
Creating JavaScript Class
JavaScript class is similar to the Javascript constructor function.
The constructor function is defined as:
// constructor function
function Person () {
[Link] = 'John',
[Link] = 23
}
// create an object
const person1 = new Person();
Instead of using the function keyword, you use the class keyword for
creating JS classes. For example,
// creating a class
class Person {
constructor(name) {
[Link] = name;
}
}
The class keyword is used to create a class. The properties are assigned
in a constructor function.
Now you can create an object. For example,
// creating a class
class Person {
constructor(name) {
[Link] = name;
}
}
// creating an object
const person1 = new Person('John');
const person2 = new Person('Jack');
[Link]([Link]); // John
[Link]([Link]); // Jack
Here, person1 and person2 are objects of Person class.
Note: The constructor() method inside a class gets called automatically each
time an object is created.
Javascript Class Methods
While using constructor function, you define methods as:
// constructor function
function Person (name) {
// assigning parameter values to the calling object
[Link] = name;
// defining method
[Link] = function () {
return ('Hello' + ' ' + [Link]);
}
}
It is easy to define methods in the JavaScript class. For example,
class Person {
constructor(name) {
[Link] = name;
}
// defining method
greet() {
[Link](`Hello ${[Link]}`);
}
}
let person1 = new Person('John');
// accessing property
[Link]([Link]); // John
// accessing method
[Link](); // Hello John
Getters and Setters
In JavaScript, getter methods get the value of an object and setter
methods set the value of an object.
JavaScript classes may include getters and setters. Use the get keyword
for getter methods and set for setter methods. For example,
class Person {
constructor(name) {
[Link] = name;
}
// getter
get personName() {
return [Link];
}
// setter
set personName(x) {
[Link] = x;
}
}
let person1 = new Person('Jack');
[Link]([Link]); // Jack
// changing the value of name property
[Link] = 'Sarah';
[Link]([Link]); // Sarah
Hoisting
A class should be defined before using it. Unlike functions and other
JavaScript declarations, the class is not hoisted. For example,
// accessing class
const p = new Person(); // ReferenceError
// defining class
class Person {
constructor(name) {
[Link] = name;
}
}
Accessing a class before defining it throws an error.
'use strict'
Classes always follow 'use-strict'. All the code inside the class is
automatically in strict mode. For example,
class Person {
constructor() {
a = 0;
[Link] = a;
}
}
let p = new Person(); // ReferenceError: Can't find variable: a
Note: JavaScript class is a special type of function. And the typeof operator
returns function for a class.
For example,
class Person {}
[Link](typeof Person); // function