This cheat sheet provides a quick reference guide for declaring and using classes, creating objects, inheritance, and other OOP (Object-Oriented Programming) concepts in JavaScript.
Class Declaration
Classes can be declared using the class keyword, followed by the class name, constructor function, and other class methods.
class ClassName {
constructor() {
// constructor logic
}
method1() {
// method1 logic
}
method2() {
// method2 logic
}
}
Class Expression
Classes can also be created using a class expression, which assigns an unnamed class to a variable.
const ClassName = class {
constructor() {
// constructor logic
}
method1() {
// method1 logic
}
method2() {
// method2 logic
}
}
Class Inheritance
Inheritance allows a child class to inherit properties and methods from a parent class. This can be achieved using the extends keyword.
class ChildClass extends ParentClass {
constructor() {
super();
// child constructor logic
}
method1() {
// child method1 logic
}
method2() {
super.method2(); // call parent method2
// child method2 logic
}
}
Getter and Setter Methods
Getter and Setter methods allow developers to define special methods for accessing and modifying properties of an object.
class ClassName {
constructor() {
// constructor logic
}
get propertyName() {
// get logic
}
set propertyName(value) {
// set logic
}
}
Static Methods
Static methods are methods that belong to the class itself rather than an instance of the class. They can be accessed without creating an object.
class ClassName {
constructor() {
// constructor logic
}
static staticMethod() {
// static method logic
}
}
Creating an Object
Objects or class instances can be created from a class using the new keyword.
const objectName = new ClassName();
Prototypes
Prototypes are objects that define methods and properties for other objects. In JavaScript, every object has a prototype.
function ClassName() {
// constructor logic
}
ClassName.prototype.method1 = function() {
// method1 logic
}
ClassName.prototype.method2 = function() {
// method2 logic
}
inheritance using Prototypes
Inheritance can also be achieved using prototypes by creating a child prototype that inherits from a parent prototype.
function ChildClass() {
ParentClass.call(this);
// child constructor logic
}
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;
ChildClass.prototype.method1 = function() {
// child method1 logic
}
ChildClass.prototype.method2 = function() {
ParentClass.prototype.method2.call(this); // call parent method2
// child method2 logic
}
Afterword
For those with long experience with JavaScript, this cheat sheet will help you look up and review classes and OOP quickly. For newcomers, it will give you an overview of classes and OOP in JavaScript.
If you want more specific instructions with more detailed examples, read the articles in this series.