Cheatsheets / Learn JavaScript
Classes
Static Methods
Within a JavaScript class, the static keyword de nes a
static method for a class. Static methods are not called class Dog {
on individual instances of the class, but are called on the constructor(name) {
class itself. Therefore, they tend to be general (utility) this._name = name;
methods. }
introduce() {
[Link]('This is ' + this._name
+ ' !');
}
// A static method
static bark() {
[Link]('Woof!');
}
}
const myDog = new Dog('Buster');
[Link]();
// Calling the static method
[Link]();
Class
JavaScript supports the concept of classes as a syntax for
creating objects. Classes specify the shared properties class Song {
and methods that objects produced from the class will constructor() {
have. [Link];
When an object is created based on the class, the new
[Link];
object is referred to as an instance of the class. New
}
instances are created using the new keyword.
The code sample shows a class that represents a Song . A
new object called mySong is created underneath and the
play() {
.play() method on the class is called. The result would [Link]('Song playing!');
be the text Song playing! printed in the console. }
}
const mySong = new Song();
[Link]();
Class Constructor
Classes can have a constructor method. This is a special
method that is called when the object is created class Song {
(instantiated). Constructor methods are usually used to constructor(title, artist) {
set initial values for the object. [Link] = title;
[Link] = artist;
}
}
const mySong = new Song('Bohemian
Rhapsody', 'Queen');
[Link]([Link]);
Class Methods
Properties in objects are separated using commas. This is
not the case when using the class syntax. Methods in class Song {
classes do not have any separators between them. play() {
[Link]('Playing!');
}
stop() {
[Link]('Stopping!');
}
}
extends
JavaScript classes support the concept of inheritance —
a child class can extend a parent class. This is // Parent class
accomplished by using the extends keyword as part of class Media {
the class de nition. constructor(info) {
Child classes have access to all of the instance properties [Link] = [Link];
and methods of the parent class. They can add their own
[Link] = [Link];
properties and methods in addition to those. A child class
}
constructor calls the parent class constructor using the
super() method.
}
// Child class
class Song extends Media {
constructor(songData) {
super(songData);
[Link] = [Link];
}
}
const mySong = new Song({
artist: 'Queen',
name: 'Bohemian Rhapsody',
publishDate: 1975
});