Saturday, March 3, 2018

JavaScript Basics II

Hello Everyone,

This is the continuation of my 1st JS Basics post, In this post I will talk about Inheritance hierarchy with Prototyping objects and What Closure is?

Let's first talk about how inheritance is implemented using JS... 



In here Car extends from Vehicle class.Drive is a prototype object of class Vehicle.For the car to use that object, Car creates a object from Vehicle prototype and access the drive method of Vehicle using car.drive().

In here if we set this.model = model inside Car function as Vehicle('car'), property will be set to car in DOM(Document Object Model) but it gives an undefine case in the console.


Also when we use Vehicle.call(this, 'car') console will give the output as Car but DOM gives a no type scenario.

As prototypes doesn't inherit properties of parent class Vehicle, console.log(car.type) is undefined.

Output to the console




What is a Closure?

Closure is refers to as function which invokes/returns another function.Simply function inside another function.Let's simplifies this by using an example.





In here printAmount is the main function and I have written another function inside of that function print() which prints percentage calculation.That function is equals to a variable which returns from main function.

Then printAmount function is called from outside which execute both the functions and prints the console.log part in the sub function.

Output to the console





Let's meet again with some indepth about Node.js in the next post.


©Copyright Viraj Wickramasinghe.

No comments:

Post a Comment