JAVSCRIPT OOP

JUNE, 2016

WHAT IS OOP?

OOP stands for Objected Oriented Programming.

The main principles are:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

WHAT IS DIFFERENT?

  • There is no class in Javascript
  • Every component in JavaScript is an Object, including Functions, Strings, and Numbers. 
  • Uses object literals or constructor functions to create objects
  • Uses prototype inheritance

OBJECT CREATION

Function as a constructor:

var cat = {};

cat.weight = 3;
cat.age = 1;

Object literal:

var cat = new Cat(3, 1);

function Cat(weight, age) {
    this.weight = weight;
    this.age = age;
}

ENCAPSULATION

  • Concept: enclosing all the functionalities of an object within that object.
  • Then we can instantiate an instance of User using User constructor.

POLYMORPHISM

The ability to redefine methods for derived classes.

INHERITANCE

In JavaScript, we don't have the concept of class, so inheritance in JavaScript is prototype based. This means to implement inheritance in JavaScript, an object inherits from another object.

PROTOTYPE

Advantage of using the prototype object to add functions:

  • No matter how many objects you create, functions are loaded only once into memory;
  • Allows you to override function if required.

CHAINING

var cat = new Cat(3, 1);

function Cat(weight, age) {
    this.weight = weight;
    this.age = age;

    this.eat = function () {
        alert("I want more!");

        return this;
    }
}

cat.eat().eat().eat();

MV* PATTERN

JS FRAMEWORKS

Practice

By sinelshchikovigor

Practice

  • 997