Skip to main content

Command Palette

Search for a command to run...

Understanding Object Oriented Programming(OOP)

A beginners introduction to the basic concepts of OOP

Published
4 min read
Understanding Object Oriented Programming(OOP)
O

Hi there 🤗 , I am Mary Okosun! I am a back-end developer based in Lagos, Nigeria. I enjoy writing about my experiences and new technologies in JavaScript and its frameworks. When I am not coding or writing articles, I see a movie or play volleyball.

In my younger years as a developer, understanding OOP seemed impossible. However, thanks to my awesome Javascript mentor at the She Code Africa Community, I was able to finally understand the concepts of OOP. I am writing this article for every developer who has had/is having issues understanding the basic concepts of Object Oriented Programming. images (5).jpeg

  • What is Object Oriented Programming?

  • Constructor

  • Instanceof

  • Prototype

  • Prototype Chaining

What is Object Oriented Programming?

Object Oriented Programming is a programming paradigm in which programs are written around objects and data.

Objects includes tangible things we can observe and interact with such as a car, a shop or a bird. Data are the properties also known as the qualities that defines what makes up an object, such as a car has wheels, a shop has items and a bird has wheels. Although similar objects share the same properties, that however may have different values for those objects. For example, all animals have legs but not all animals have same number of legs. In JavaScript, object are used to model real world objects, giving them properties. An object is created as such

let dog = {
    name: 'Gold',
    numLegs: 4
};

Values can be accessed from an object using the dot notation.

console.log(dog.name);  // Gold
console.log(dog.numLegs);  // 4

Objects can have a special type of property called Method. They are properties which are functions. Therefore, in the snippet below, sayLegs() is a method because it is a function.

let dog = {
    name: 'Gold',
    numLegs: 4,
    sayLegs: function(){
             return `This dog has ${dog.numLegs} legs`}
};

dog.sayLegs();  //This dog has 4 legs

In the above example, we accessed the value of numLegs property using the dot notation. It is necessary to note that there is a pitfall here. If the variable name changes, any references to the original name would have to updated and this could be a problem with an object with many references. A way to avoid these issues is to use the ‘this’ keyword.

sayLegs: function(){ return `This dog has ${this.numLegs} legs`}

Constructor

Constructors are function that create new objects. The below constructor defines a Dog object with name, color and numLegs properties. The ‘this’ inside the constructor refers to the objects being created. Constructor are defined with capital letters to differentiate them from other functions.

function Dog() {
    this.name = 'Gold',
    this.color = 'Brown',
    this.numLegs= 4
}

The constructor property is located on the object instance. It is a reference to the constructor function that created the instance. An advantage is that it is possible to check for this property to find out what kind of object it is.

let hound = new Dog();
console.log(hound.constructor === Dog);   //true

Instanceof

An instance of Dog called hound is created and now hound has all the properties defined inside the Dog constructor.

hound.name;  //Gold
hound.color;  //Brown

It’s properties can be easily modified.

hound.name = 'Hound';
hound.name;  //Hound

However modifying properties can take a lot of time especially objects with a large number of properties. It is much more easier to modify by adding them as arguments to the constructor.

function Dog(name,color){
    this.name = name;
    this.color = color;
    this.numLegs = 4;
}
let terrier = new Dog('Terrier' ,'Red');
console.log(terrier)  //  {name: "Terrier", color: "Red", numLegs: 4}

Objects can be easily compared to a constructor by using instanceof. This returns true or false if the the object was created with the constructor or not respectively.

terrier instanceof Dog;  //true

Prototype

Another important concept is Prototype. Just like people inherit genes from their parents, an object inherits its prototype directly from the constructor function that created it. Prototype can be described as a recipe for creating objects. All objects in JavaScript including functions have a prototype property which is reference to another object. It is a way by which JS objects inherit features from one another. For example, here the Dog constructor creates the hound object.

function Dog(name){
    this.name = name;
}
let hound = new Dog('Jack');

hound inherits its prototype from the Dog constructor function. We can use isPrototypeOf method to check the prototype of an object.

Dog.prototype.isPrototypeOf(hound); //true

Prototype Chaining

An objects prototype itself is an object. Because a prototype is an object, a prototype can have its own prototype. Therefore, the prototype of Dog.prototype is object.prototype. Using this analogy,we can understand Prototype Chaining better. In this prototype chain, Dog is the supertype while hound is the subtype. Object is a supertype for both Dog and hound. Object is a supertype for all objects in JavaScript. Properties can be added to the prototype individually.

Dog.prototype.numLegs = 4;
Dog.prototype.bark = function(){
    console.log('Woof! Woof!!');
}

However, a more efficient way to do this is to set the prototype to a new object that already contains the properties.

Dog.prototype = {
    numLegs : 4,
    bark : function(){
        console.log('Woof! Woof!!')
}

Object Oriented Programming is a concept in JavaScript that might seem so broad to comprehend but with continuous learning and practice, it can be easily understood.

images (4).png

If you found this article helpful, don't forget to drop your comments and your feedbacks would be highly appreciated.

Happy coding!!!

RESOURCES

F

Really nice introductory article to OOP 👍

O

Thanks a lot @Favourite Jome Glad you found the article interesting ❣️

1
D

Nice Article.
some points that i think you missed. OOP has main four principle.

  1. Encapsulation - which is basically that an object will responsible for a specific tasks. Bundling of data, methods on that data, in one things(object).
  2. Abstraction - only exposing the useful methods to the user and hiding the complexity of the mechanism.
  3. Inheritance - is that the methods and properties can be inherited or taken from a Parent class( functions in js).
  4. Polymorphism - objects can share the same interface - how we can access them or used - their implementation may change.

ECMAScript 2015 // js now supports Classes although nothing wrong with functions. Actually almost everything in JS in an object(with key and value). JS is a very funky language. I like the Animals example the best. We create Animal class to which we can give actions - eat or sleep that all the animals do( not jellyfish because they don't have brain). Then create a Mammal class and extend it to the Animal class. That's called inheritance. Now, we can give specific methods, or data to the Mammals that will be useful for the Mammals. That's called Polymorphism. Similarly, we can create dog or cat with more polymorphism extending the mammal class.

I love OOP but i have an affair with Functional Programming.

class Animal {
  eat() {
    console.log("I'm eating");
  }
  sleep() {
    console.log("I'm sleeping")
  }
}
class Mammal extends Animal {
  constructor(legs) {
    super();
    this.legs = legs;
    this.warmBlooded = true;
   }

  giveLiveBirth() {
    //ah yes what a miracle
  }
}
class Dog extends Mammal {
  constructor(name, breed) {
    super(4);
    this.name = name;
    this.breed = breed;
  }
}
3
O

Thanks a lot for the points you noted. I discussed just Inheritance. Guess I would make a part 2 of this article then.Thanks Pratik Sharma.

1
F

I noticed you added 4 into the parenthesis of super method. I'll like to know what it's for please @pratiksharm

1
D

Sorry I didn't explain that. Favourite Jome

Super is Super cool

We use the 'extends' keyword to extend from the parent class. So, now we have access to the method that the parent class has. But what if you want to get access to the constructor function in the parent class.

What is the use of Super? and why it is used in the constructor function.

Use Case of Super:-
When we call super() -----> constructor function of the parent class().

so super(4) in the dog class which extends to the Mammal class with the constructor function

constructor(legs) { super(); this.legs = legs; this.warmBlooded = true; } here legs = 4, So, basically that dogs will have 4 legs by default in the dog class. That's Polymorphism.

3
F

Okay thanks, I get it now. It's just that I hadn't seen it used like that until now. Pratik Sharma

1