The Little Guide for OOP in JS

Germán Cutraro
HackerNoon.com
4 min readJan 26, 2018

--

In this guide i will try to explain the new features of es6 JavaScript focusing in the Object-Oriented Paradigm.

First of all,

What is a programming paradigm?

A paradigm is a example or model of something, so, is a pattern to follow for, in this case, create computer programms.

What is Object-Oriented?

Obviously you realize that is a programming paradigm, but like exist this option we have a lot of other options like functional programming, reactive programming etc.

What are the characteristics of this paradigm?

What we do in this paradigm is to program in a way closer to reality, we program in terms of classes, objects, methods, properties, etc., and especially integrates terms such as: abstraction, escapsulation, modularity, privacy, polymorphism, inheritance, etc.

The problem with JavaScript is that is not so a POO language, why? because in JavaScript all is a object, so we can fix this using the famous prototype.

In ES5 we can do the next sample using the factory pattern:

Now in ES6 we can do all of this in a simple way, but we must remember that is just syntactic sugar:

The last example with ES6 syntac.

In this case, with the extends keyword we just say: ‘Alright i want to inhertanced the Person class propierties’. But behind the scenes this is the same that we did in the es5 example using prototypes.

Static Methods:

Private Methods

In JavaScript we don’t have the private keyword like Java and C# have, something important is that in JavaScript we have a convention to use for ‘private’ values, that convention is to use a underscore before the word, let me show you:

Nevertheless in ES6 we have a object call WeakMap that allows us to create private propierties, let’s see:

Getters and Setters

When we have private methods is usual that create a public method that return the private value, so we have get to return a value and set to define a new value.

Polymorphism

Is the ability for an object during execution, to reference either an occurrence of his class or an occurrence of any of his descendants classes. Descendants classes may redefine a method.

Some Concepts:

class: Creation of a new class/model.
method: function inside a class.
constructor: Method that initializes an object when the class is instantiated.
extends: Used for set a inheritance.
super: Method that set the inheritance properties calling the father. constructor. The supe must be in the first line of the constructor method.
get: Method to return a value.
set: Method to re-define a new existing value.
new: Creation of an object by the class constructor method.

You can go to my Github to find JavaScript examples.

Thank you 😊!

--

--