Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

The Complete Guide to JavaScript Classes

Posted December 11, 2019


javascriptclassinstanceof
8 Comments
JavaScript uses prototypal inheritance: every object inherits properties
and methods from its prototype object.
The traditional class as the blueprint to create objects, used in languages
like Java or Swift, does not exist in JavaScript. The prototypal
inheritance deals only with objects.
The prototypal inheritance can emulate the classic class inheritance. To
bring the traditional classes to JavaScript, ES2015 standard introduces
the class syntax: a syntactic sugar over the prototypal inheritance.
This post familiarizes you with JavaScript classes: how to define a class,
initialize the instance, define fields and methods, understand the private
and public fields, grasp the static fields and methods.

1. Definition: class keyword


The special keyword class defines a class in JavaScript:
class User {
// The body of class
}

The code above defines a class User. The curly braces { } delimit the
class body. Note that this syntax is named class declaration.
You’re not obligated to indicate the class name. By using a class
expression you can assign the class to a variable:
const UserClass = class {
// The body of class
};
You can easily export a class as part of an ES2015 module. Here’s the
syntax for a default export:
export default class User {
// The body of class
}

And a named export:


export class User {
// The body of class
}

The class becomes useful when you create an instance of the class. An
instance is an object containing data and behavior described by the class.

You might also like