A Step ahead about Objects in Javascript.

A Step ahead about Objects in Javascript.

Everytime you learn about a new programming language, you always get to hear about a term known as "OOPS" or Object Oriented Programming Paradigm.

While, Javascript natively is not a ClassBased Object Oriented Programming Language, but it still has ways of using OOPs.

One of such feature of OOP is 'Inheritence'

Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more.

Using inheritance, an object can inherit all the methods and properties of another object.

Inheritance is a useful feature that allows code reusability.

Uses of Inheritance

-Since a child can inherit all the functionalities of the parent's , this allows code reusability.

-Once a functionality is developed, you can simply inherit it. No need to reinvent the wheel. This allows for cleaner code and easier to maintain.

-Since you can also add your own functionalities in the child class, you can inherit only the useful functionalities and define other required features.

So, this is what Inheritance means in a nutshell.

Everything is an object in JavaScript. We don't create class to get the object. But, we direct create objects instead.

so In Javascript, Non Primitive Datatype :objects have a special hidden property [[Prototype]](as named in the specification), that is either null or references another object. That object is called “a prototype”.

So properties and methods that are defined they will bind most tightly to its actual definition.

Example:

let myarray = []

myarray['test'] = 'abcd'

//myarray= [test:'abcd']

Array.prototype.test = 'defg'

//What would be the o/p

myarray.test ?

Even though we declared the prototype later, you might think it overwrites the value, is'nt it? It Does'nt!

Because this is bound more tightly to the array variable, therefore this will output abcd

Note: Properties/Methods are defined most tightly to the instance have priority.

Non Primitives Types has few methods associated with them, Array.prototype.push() String.prototype.toUpperCase()

Primitives Types don't have methods associated with them, however they have object wrappers and JS will automatically wrap primitive values so you have the access to methods

42.toString()   //Error

var x = 42
x.toString()     // "42"

x.__proto__      // [Number: 0]
x instanceof Number     //false

In the above example, when JS after you have declared a variable x as 42, which is in turn a primitive and it doesn't have any methods attached to it ex. toString()... However, It automatically treat it as the object if JS sees that we are trying to access these methods.

Thats it! Thanks for reading.