DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on

OOPS in JS

Prototype:

Image description

This prototype object is basically parent class in javascript because in only few instances we will see that js actually has classes as it works mostly on objects and so we coined the term Prototyping.

In this case the map is a function of the prototype object of array which is acessible by all the arrays.

Note: So we can say that the array num inherits the map method from the array prototype object.

Methods of Creating an Object

Image description

Constructor functions
The first way was the most used and that's how basically we declare our data structure objects like arra, map, etc.

ES6 Classes
Provides 1 extra layer of abstraction and a more better looking way of creating an object from constructor functions.

Object.create()
Easiest way but seldom used.

NEW keyword (Function constructor)

Image description

Note down these 4 points
Never include methods inside a function constructor for an object -> as it will create space for itself every-time a new object is created with that function constructor.

Instead we should use Prototype

Prototype

Image description

Using this we created a method for the object Person

The Difference

Image description
Notice how there is calcAge() defined for the object itself when the method is defined inside the constructor class whereas it's(calcAge()) not directly part of the Person object in case of Prototype but is still accessible via an object(jonas) of Person.

Who's prototype is it?

Image description

Output ->
Image description

It shows here that it is not the object Person's prototype rather it is the object's prototype that is created through that constructor function.
B'coz this proto is created as and when this new keyword is called.

Property

Image description

Output->
Image description

And so now we see that species is not a property but a prototype variable of the object(jonas/matilda..).

Classes

Ways to declare a class

1> Expression
2> traditional way

Image description

Prototype

Image description

Hence a function declared inside a class is included in the proto section

Classes ** and **objects both are not hoisted.
Classes are first-class citizens which can be passed as arguments to functions and also can be returned from functions.

Classes are executed in strict mode.

Top comments (0)