0% found this document useful (0 votes)
26 views6 pages

Classes in JavaScript

This document provides an overview of classes in JavaScript, detailing how to create classes, constructors, inheritance, and encapsulation. It explains the use of the 'class' keyword, the 'extends' keyword for inheritance, and the implementation of private fields and methods. The article serves as a guide for understanding object-oriented programming concepts within JavaScript, emphasizing the prototype-based nature of the language.

Uploaded by

curvesmakers
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views6 pages

Classes in JavaScript

This document provides an overview of classes in JavaScript, detailing how to create classes, constructors, inheritance, and encapsulation. It explains the use of the 'class' keyword, the 'extends' keyword for inheritance, and the implementation of private fields and methods. The article serves as a guide for understanding object-oriented programming concepts within JavaScript, emphasizing the prototype-based nature of the language.

Uploaded by

curvesmakers
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Classes in JavaScript - Learn web development | MDN 25.02.

26, 00:32

Learn Extension modu0es Advanced JavaScript objects C0asses in JavaScript Eng0ish (US)

C"asses in JavaScript
Previous Overview: Advanced JavaScript objects Next

<n the 0ast artic0e, we introduced some basic concepts of object-oriented programming (OOP), and discussed an
examp0e where we used OOP princip0es to mode0 professors and students in a schoo0.

We a0so ta0ked about how it's possib0e to use prototypes and constructors to imp0ement a mode0 0ike this, and that
JavaScript a0so provides features that map more c0ose0y to c0assica0 OOP concepts.

<n this artic0e, we'00 go through these features. <t's worth keeping in mind that the features described here are not a
new way of combining objects: under the hood, they sti00 use prototypes. They're just a way to make it easier to set
up a prototype chain.

Fami0iarity with JavaScript basics (especia00y Object basics) and object-oriented JavaScript
Prerequisites:
concepts covered in previous 0essons in this modu0e.

Creating c0asses in JavaScript.


Learning
Creating constructors in JavaScript.
outcomes:
<nheritance and encapsu0ation in JavaScript.

C"asses and constructors


You can dec0are a c0ass using the class keyword. Here's a c0ass dec0aration for our Person from the previous
artic0e:

JS

[Link] Page 1 of 7
Classes in JavaScript - Learn web development | MDN 25.02.26, 00:32

class Person {
name;

constructor(name) {
[Link] = name;
}

introduceSelf() {
[Link](`Hi! I'm ${[Link]}`);
}
}

This dec0ares a c0ass ca00ed Person , with:

a name property.
a constructor that takes a name parameter that is used to initia0ize the new object's name property
an introduceSelf() method that can refer to the object's properties using this .

The name; dec0aration is optiona0: you cou0d omit it, and the 0ine [Link] = name; in the constructor wi00 create
the name property before initia0izing it. However, 0isting properties exp0icit0y in the c0ass dec0aration might make it
easier for peop0e reading your code to see which properties are part of this c0ass.

You cou0d a0so initia0ize the property to a defau0t va0ue when you dec0are it, with a 0ine 0ike name = ''; .

The constructor is defined using the constructor keyword. Just 0ike a constructor outside a c0ass definition, it wi00:

create a new object


bind this to the new object, so you can refer to this in your constructor code
run the code in the constructor
return the new object.

Given the c0ass dec0aration code above, you can create and use a new Person instance 0ike this:

JS

const giles = new Person("Giles");

[Link](); // Hi! I'm Giles

Note that we ca00 the constructor using the name of the c0ass, Person in this examp0e.

Omitting constructors

[Link] Page 2 of 7
Classes in JavaScript - Learn web development | MDN 25.02.26, 00:32

<f you don't need to do any specia0 initia0ization, you can omit the constructor, and a defau0t constructor wi00 be
generated for you:

JS

class Animal {
sleep() {
[Link]("zzzzzzz");
}
}

const spot = new Animal();

[Link](); // 'zzzzzzz'

.nheritance
Given our Person c0ass above, 0et's define the Professor subc0ass.

JS

[Link] Page 3 of 7
Classes in JavaScript - Learn web development | MDN 25.02.26, 00:32

class Professor extends Person {


teaches;

constructor(name, teaches) {
super(name);
[Link] = teaches;
}

introduceSelf() {
[Link](
`My name is ${[Link]}, and I will be your ${[Link]} professor.`,
);
}

grade(paper) {
const grade = [Link]([Link]() * (5 - 1) + 1);
[Link](grade);
}
}

We use the extends keyword to say that this c0ass inherits from another c0ass.

The Professor c0ass adds a new property teaches , so we dec0are that.

Since we want to set teaches when a new Professor is created, we define a constructor, which takes the name
and teaches as arguments. The first thing this constructor does is ca00 the superc0ass constructor using super() ,
passing up the name parameter. The superc0ass constructor takes care of setting name . After that, the Professor
constructor sets the teaches property.

Note: <f a subc0ass has any of its own initia0ization to do, it must first ca00 the superc0ass constructor using
super() , passing up any parameters that the superc0ass constructor is expecting.

We've a0so overridden the introduceSelf() method from the superc0ass, and added a new method grade() , to
grade a paper (our professor isn't very good, and just assigns random grades to papers).

With this dec0aration we can now create and use professors:

JS

[Link] Page 4 of 7
Classes in JavaScript - Learn web development | MDN 25.02.26, 00:32

const walsh = new Professor("Walsh", "Psychology");


[Link](); // 'My name is Walsh, and I will be your Psychology professor'

[Link]("my paper"); // some random grade

Encapsu"ation
Fina00y, 0et's see how to imp0ement encapsu0ation in JavaScript. <n the 0ast artic0e we discussed how we wou0d 0ike to
make the year property of Student private, so we cou0d change the ru0es about archery c0asses without breaking
any code that uses the Student c0ass.

Here's a dec0aration of the Student c0ass that does just that:

JS

class Student extends Person {


#year;

constructor(name, year) {
super(name);
this.#year = year;
}

introduceSelf() {
[Link](`Hi! I'm ${[Link]}, and I'm in year ${this.#year}.`);
}

canStudyArchery() {
return this.#year > 1;
}
}

<n this c0ass dec0aration, #year is a private fie0d. We can construct a Student object, and it can use #year
interna00y, but if code outside the object tries to access #year the browser throws an error:

JS

[Link] Page 5 of 7
Classes in JavaScript - Learn web development | MDN 25.02.26, 00:32

const summers = new Student("Summers", 2);

[Link](); // Hi! I'm Summers, and I'm in year 2.


[Link](); // true

summers.#year; // SyntaxError

Note: Code run in the Chrome conso0e can access private e0ements outside the c0ass. This is a DevToo0s-
on0y re0axation of the JavaScript syntax restriction.

Private fie0ds must be dec0ared in the c0ass dec0aration, and their names start with # .

Private methods
You can have private methods as we00 as private fie0ds. Just 0ike private fie0ds, private methods' names start with # ,
and they can on0y be ca00ed by the object's own methods:

JS

class Example {
somePublicMethod() {
this.#somePrivateMethod();
}

#somePrivateMethod() {
[Link]("You called me?");
}
}

const myExample = new Example();

[Link](); // 'You called me?'

myExample.#somePrivateMethod(); // SyntaxError

Summary
<n this artic0e, we've gone through the main too0s avai0ab0e in JavaScript for writing object-oriented programs. We

[Link] Page 6 of 7

You might also like