paint-brush
The Little Guide for OOP in JSby@germancutraro
17,303 reads
17,303 reads

The Little Guide for OOP in JS

by Germán CutraroJanuary 26th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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

Company Mentioned

Mention Thumbnail
featured image - The Little Guide for OOP in JS
Germán Cutraro HackerNoon profile picture

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:

console.log('*** PERSON ***');




















function Person (name) {this.name = name;}// We define our properties/methodsPerson.prototype = {eyes: 2,mouth: 1,sleep: function () {return 'zzz';}};// We create a personconst p1 = new Person('Nick');// and we can do:console.log(`name: ${p1.name}`,`eyes: ${p1.eyes}`,`mouth: ${p1.mouth}`,p1.sleep());

console.log('*** EMPLOYEE ***')



















// But now, if we have a employee 'class' we can inheritance person's properties.function Employee (name, salary) {this.name = name;this.salary = salary;}// Prototype InheritanceEmployee.prototype = Object.create(Person.prototype);Employee.prototype.constructor = Employee; // Set his own constructor// So now, we just can do the same thing// We create a employeeconst em1 = new Employee('John', 3000);// and we can do:console.log(`name: ${em1.name}`,`salary: ${em1.salary} USD`,`eyes: ${em1.eyes}`,`mouth: ${em1.mouth}`,em1.sleep());

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.










class Person {constructor (name) {this.name = name;this.eyes = 2;this.mouth = 1;}sleep () {return 'zzz';}}






class Employee extends Person {constructor (name, salary) {super(name);this.salary = salary;}}








const p1 = new Person('Nick');// and we can do:console.log(`name: ${p1.name}`,`eyes: ${p1.eyes}`,`mouth: ${p1.mouth}`,p1.sleep());










// We create a employeeconst em1 = new Employee('John', 3000);// and we can do:console.log(`name: ${em1.name}`,`salary: ${em1.salary} USD`,`eyes: ${em1.eyes}`,`mouth: ${em1.mouth}`,em1.sleep());

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:





class Dog {static whatIs() {return 'A dog is a beatiful animal';}}


// So, with static we can access to methods without the need to instantiate a new object of the class.console.log( Dog.whatIs() );

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:









class Person {constructor (name, phone) {this.name = name;this._phone = phone;}}const p1 = new Person('John', 544342212);// But 'phone' is not a private propertie because we can do this:console.log(p1._phone);

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











// Don't use private like variable name because is a reserved wordconst secret = new WeakMap();class Person {constructor (name, phone) {this.name = name;secret.set(this, {_phonenumber: phone});}}const p1 = new Person('John', 544342212);// Now the phonenumber is a private propertie.console.log(p1._phone); // Print's undefined

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.


















const secret = new WeakMap();class Person {constructor (name, phone) {this.name = name;secret.set(this, {_phonenumber: phone});}get phoneNumber() {return secret.get(this)._phonenumber;}set phoneNumber(newNumber) {secret.get(this)._phonenumber = newNumber;}}const p1 = new Person('John', 544342212);// Now we can access to the phone by using the getter:console.log(p1.phoneNumber); // Print's the number// Set a new numberp1.phoneNumber = 432232323;console.log(p1.phoneNumber); // We get the new number

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.




















class Person {constructor(name) {this.name = name;}me() {return `My name is ${this.name}`;}}const axel = new Person('Axel');console.log(axel.me());// -> 'My name is Axel'class Employee extends Person {constructor (name, salary) {super(name);this.salary = salary;}me() {return `My name is ${this.name} and my salary is ${this.salary}`;}}



const nick = new Employee('Nick', 3000);console.log(nick.me());// -> 'My name is Nick and my salary is 3000'

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 😊!