Classes in JavaScript was introduced in the ES6/ECMAScript2015. A class is a type of function with keyword class
. Class is executed in strict mode, So the code containing the silent error or mistake throws an error. JavaScript classes can have a constructor method, which is a special method that is called each time when the object is created. Constructor methods are usually used to set initial values for the objects.
class Song {
constructor() {
this.name;
this.songBy;
}
play() {
console.log('Song is playing...!');
}
}
const mySong = new Song();
mySong.play();
Classes in JavaScript supports the concept of inheritance, which means a child class can extend a parent class using the extends
keyword. Child classes have their own properties and methods, and it has access to all the properties and methods of the parent class. A child class constructor calls the parent class constructor using the super()
method.
// parent class
class Categories {
constructor(songData) {
this.categoryName = songData.categoryName;
this.categoryDetails = songData.categoryDetails;
}
}
// child class
class Song extends Categories {
constructor(songData) {
super(songData);
this.artist = songData.artist;
}
}
const mySong = new Song({
artist: 'Artist',
categoryName: 'New Song',
categoryDetails: 2020
});
JavaScript classes have their own properties and methods, which can be defined as static using static
keyword. Static properties and methods inside the class can't be accessed using its objects, instead it can be accessed using class itself.
class Car {
constructor(name) {
this.name = name;
}
introduce() {
console.log('This is ' + this.name + ' !');
}
static run() {
console.log('Car is running...!');
}
}
const myCar = new Car('My Car');
myCar.introduce();
// Calling the static method using class name
Car.run();
Object in JavaScript is a unique entity which contains property and methods. Most of the times, variables or arrays are not sufficient to simulate real-life situations, and to deal with such situations JavaScript allows you to create objects.
Creating an Object:- A JavaScript object can be created like below-
let objectName = new Object();
objectName.property1 = value1;
objectName.property2 = value2;
objectName.property3 = function() {
// line of code
}
A JavaScript object can also be created like below-
let objectName = {
property1 = value1;
property2 = value2;
property3 = function() {
// line of code
}
}
Accessing an Object Properties:- A JavaScript object properties can be easily accessed like below-
objectName.propertyName;
A JavaScript object properties can also be accessed like below-
objectName["propertyName"];