Professional Documents
Culture Documents
An introduction to Object-Oriented
Programming in JavaScript
This article is for students of JavaScript that don’t have any prior
knowledge in object-oriented programming (OOP). I focus on the parts of
OOP that are only relevant for JavaScript and not OOP in general. I skip
polymorphism because it ts better with a static-typed language.
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 1/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
Di erent Mindsets
In football, you can play from a safe defense, you can play with high
balls from the sides or you can attack like there is no tomorrow. All
these strategies have the same objective: To win the game.
The same is true for programming paradigms. There are di erent ways
to approach a problem and design a solution.
If you were like me when I heard it the rst time, you have no clue what
this actually means — it all sounds very abstract. Feeling that way is
absolutely ne. It’s more important that you’ve heard the idea,
remember it, and try to apply OOP in your code. Over time, you will
gain experience and align more of your code with this theoretical
concept.
Lesson: OOP based on real-world objects lets anyone read your code
and understand what’s going on.
Object as Centerpiece
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 2/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
A simple example will help you see how JavaScript implements the
fundamental principles of OOP. Consider a shopping use case in which
you put products into your basket and then calculate the total price you
must pay. If you take your JavaScript knowledge and code the use case
without OOP, it would look like this:
The OOP version of the shopping use case could be written like:
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 3/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
As you can see in the rst line, we create a new object by using the
keyword new followed by the name of what’s called a class (described
below). This returns an object that we store to the variable bread. We
repeat that for the variable water and take a similar path to create a
variable basket. After you have added these products to your basket,
you nally print out the total amount you have to pay.
The di erence between the two code snippets is obvious. The OOP
version almost reads like real English sentences and you can easily tell
what’s going on.
Class as Template
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 4/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
You can look at classes like the blueprints for a car. They de ne the car’s
properties like torque and horsepower, internal functions such as air-to-
fuel ratios and publicly accessible methods like the ignition. It is only
when a factory instantiates the car, however, that you can turn the key
and drive.
In our use case, we use the Product class to instantiate two objects,
bread and water. Of course, those objects need code which you have to
provide in the classes. It goes like this:
this.getName = function() {
return name;
};
this.getPrice = function() {
return price;
};
}
function Basket() {
const products = [];
this.calcTotal = function() {
return products
.map(product => product.getPrice())
.reduce((a, b) => a + b, 0);
};
this.printShoppingInfo = function() {
console.log('one has to pay in total: ' +
this.calcTotal());
};
}
A class in JavaScript looks like a function, but you use it di erently. The
name of the function is the class’s name and is capitalized. Since it
doesn’t return anything, we don’t call the function in the usual way like
const basket = Product('bread', 1); . Instead, we add the keyword
new like const basket = new Product('bread', 1); .
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 5/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
The code inside the function is the constructor. This code executes each
time an object is instantiated. Product has the parameters _name and
_price . Each new object stores these values inside it.
Encapsulation
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 6/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
Unfortunately, you have now given full access to the properties from
the outside. So everybody could access and modify it:
Objects should have exclusive control over their data. In other words,
the objects “encapsulate” their data and prevent other objects from
accessing the data directly. The only way to access the data is indirect
via the functions written into the objects.
Data and processing (aka logic) belong together. This is especially true
when it comes to larger applications where it is very important that
processing data is restricted to speci cally-de ned places.
In our case, objects of class Product don’t let you change the price or
the name after their initialization. The instances of Product are read-
only.
Inheritance
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 7/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
Let’s say we have a new class called Book that has a name, a price and
an author. With inheritance, you can say that a Book is the same as a
Product but with the additional author property. We say that Product is
the superclass of Book and Book is a subclass of Product:
this.getAuthor = function() {
return author;
}
}
You can now add a book object to the basket without any issues:
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 8/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
Even though JavaScript’s support for OOP is not at the same level as
other languages like Java, it is still evolving. The release of version ES6
added a dedicated class keyword we could use. Internally, it serves
the same purpose as the prototype property, but it reduces the size of
the code. However, ES6 classes still lack private properties, which is
why I stuck to the “old way”.
For the sake of completeness, this is how we would write the Product,
Basket and Book with ES6 classes and also with the prototype (classical
and default) approach. Please note that these versions don’t provide
encapsulation:
// ES6 version
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 9/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
class Basket {
constructor() {
this.products = [];
}
addProduct(amount, product) {
this.products.push(…Array(amount).fill(product));
}
calcTotal() {
return this.products
.map(product => product.price)
.reduce((a, b) => a + b, 0);
}
printShoppingInfo() {
console.log('one has to pay in total: ' +
this.calcTotal());
}
}
//Prototype version
function Basket() {
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 10/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
this.products = [];
}
Basket.prototype.addProduct = function(amount, product) {
this.products.push(...Array(amount).fill(product));
};
Basket.prototype.calcTotal = function() {
return this.products
.map(product => product.price)
.reduce((a, b) => a + b, 0);
};
Basket.prototype.printShoppingInfo = function() {
console.log('one has to pay in total: ' +
this.calcTotal());
};
Summary
As a new programmer learning JavaScript, it will take time to
appreciate Object-Oriented Programming fully. The important things to
understand at this early stage are the principles the OOP paradigm is
based on and the bene ts they provide:
Further reading
• https://developer.mozilla.org/en-
US/docs/Learn/JavaScript/Objects/Object-oriented_JS
• http://voidcanvas.com/es6-private-variables/
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 11/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
• https://medium.com/@rajaraodv/is-class-in-es6-the-new-bad-
part-6c4e6fe1ee65
• https://developer.mozilla.org/en-
US/docs/Learn/JavaScript/Objects/Inheritance
* https://en.wikipedia.org/wiki/Object-oriented_programming
• https://en.wikipedia.org/wiki/Object-oriented_programming
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 12/13
11/21/2018 An introduction to Object-Oriented Programming in JavaScript
https://medium.freecodecamp.org/an-introduction-to-object-oriented-programming-in-javascript-8900124e316a 13/13