Skip to content

Instantly share code, notes, and snippets.

@garrettmac
Created September 15, 2017 04:31
Show Gist options
  • Save garrettmac/24fb9b0f91554cbf28f5a568c9602f6b to your computer and use it in GitHub Desktop.
Save garrettmac/24fb9b0f91554cbf28f5a568c9602f6b to your computer and use it in GitHub Desktop.
MEDIUM BLOG POST - Javascript’s 3 Major Paradigms: The Three tenets of Object Oriented Programming [part 2 of 4]

Javascript Paradigms

1. Object Oriented Programming (OOP) Paradigms

What is OOP?

What?

Object Oriented Programming (OOP) refers to using self-contained pieces of code to develop applications. We call these self-contained pieces of code objects, better known as Classes in most OOP programming languages and Functions in JavaScript.


Objects can be thought of as the main actors in an application, or simply the main “things” or building blocks that do all the work. As you know by now, objects are everywhere in JavaScript since every component in JavaScript is an Object, including Functions, Strings, and Numbers.

Why?

How?

Through object literals (Encapsulation)

var myObj = {name: "Richard", profession: "Developer"};

or constructor functions (Inheritance)

  function Employee () {}

  
   Employee.prototype.firstName = "Abhijit";
   Employee.prototype.lastName = "Patel";
   Employee.prototype.startDate = new Date();
   Employee.prototype.signedNDA = true;
   Employee.prototype.fullName = function () {
   console.log (this.firstName + " " + this.lastName);
   };
  | ​
   ​var abhijit = new Employee () //​
   console.log(abhijit.fullName()); // Abhijit Patel​
   console.log(abhijit.signedNDA); // true

to create objects in the OOP design pattern


The Three tenets of Object Oriented Programming (OOP):

1. Inheritance

The Best Inheritance Pattern

Parasitic Combination Inheritance

What?

Inheritance (objects can inherit features from other objects)

Inheritance refers to an object being able to inherit methods and properties from a parent object (a Class in other OOP languages, or a Function in JavaScript).

Why?

Lets say we have a quiz application to make different types of Questions. We will implement a MultipleChoiceQuestion function and a DragDropQuestion function. To implement these, it would not make sense to put the properties and methods outlined above (that all questions will use) inside the MultipleChoiceQuestion and DragDropQuestion functions separately, repeating the same code. This would be redundant.

Instead, we will leave those properties and methods (that all questions will use) inside the Question object and make the MultipleChoiceQuestion and DragDropQuestion functions inherit those methods and properties.

This is where inheritance is important: we can reuse code throughout our application effectively and better maintain our code.

How?

An instance is an implementation of a Function. In simple terms, it is a copy (or “child”) of a Function or object. For example:

// Tree is a constructor function because we will use new keyword to invoke it.​
   ​function Tree (typeOfTree) {}
   ​
   ​// bananaTree is an instance of Tree.​
  ​var bananaTree = new Tree ("banana");

In the preceding example, bananaTree is an object that was created from the Tree constructor function. We say that the bananaTree object is an instance of the Tree object. Tree is both an object and a function, because functions are objects in JavaScript. bananaTree can have its own methods and properties and inherit methods and properties from the Tree object, as we will discuss in detail when we study inheritance below.

using the Parasitic Combination Inheritance Using the *Object.create() Method

 if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {
        }F.prototype = o;
        return new F();
    };
}

Let’s quickly understand it is doing.

Object.create = function (o) {//It creates a temporary constructor F()​
        function F() {
        }//And set the prototype of the this constructor to the parametric (passed-in) o object​//so that the F() constructor now inherits all the properties and methods of o​
        F.prototype = o;
​
​//Then it returns a new, empty object (an instance of F())​//Note that this instance of F inherits from the passed-in (parametric object) o object. ​//Or you can say it copied all of the o object's properties and methods​
        return new F();
    }

2. Encapsulation

What?

Encapsulation (each object is responsible for specific tasks).

The Best Object Creation Pattern:

Combination Constructor/Prototype Pattern

Encapsulation refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application.

Why?

This allows us to abstract or localize specific set of functionalities on objects.

How?

To implement encapsulation in JavaScript, we have to define the core methods and properties on that object. To do this, we will use the best pattern for encapsulation in JavaScript: the Combination Constructor/Prototype Pattern.

function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
    this.quizScores = [];
    this.currentScore = 0;
}User.prototype = {
    constructor: User,
    saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
} 

When?

when you want to create objects with similar functionalities (to use the same methods and properties), you encapsulate the main functionalities in a Function and you use that Function’s constructor to create the objects. This is the essence of encapsulation. And it is this need for encapsulation that we are concerned with and why we are using the Combination Constructor/Prototype Pattern.


3. Polymorphism
### What? Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ)

In JavaScript it is a bit more difficult to see the effects of polymorphism because the more classical types of polymorphism are more evident in statically-typed systems, whereas JavaScript has a dynamic type system.

Why?

Polymorphism foster many good attributes in software, among other things it fosters modularity and reusability and make the type system more flexible and malleable

How?

This is not simple to answer, different languages have different ways to implement it. In the case of JavaScript, as mentioned above, you will see it materialize in the form of type hierarchies using prototypal inheritance and you can also exploit it using duck typing.

What is polymorphism in Javascript? - https://stackoverflow.com/questions/27642239/what-is-polymorphism-in-javascript


OOP key words

Encapsulation - object literals Inheritance - constructor functions and new keyword

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment