YDKJS — Objects and Prototypes — Part1

Image for post
Image for post
Don’t know JS

Welcome to the second series of You don’t know JS. Part one of the series regarding Scopes and Closures is here.

This series is all from the learnings of Kyle Simpson and also from the amazing youtube Javascript series by Kaushik Kothagul from Javabrains, which is also influenced by You don’t know JS.

Let’s start with creating a simple function using object to create employee objects.

Now consider the line var newObj = {}; and return newObj; They will be same in every function which we create. So, JS gave us a special type of function known as Constructor function to create them.

We will refactor the above to use Constructor function. Look at the below code.

We are adding the keyword new to create the object. It basically takes care of the creation and returning of the newObj. But gives this a new name this.
Note, that we don’t need to put those two line in our code and automatically put by JS engine.

Let’s go through the four different ways to execute functions in Javascript.

The Method#1 is the obvious way to execute a function.
In Method#2 , we have an object and that object have a property of foo. The property foo have a value as anonymous function. So, obj.foo() can be used to call the function.
The Method #3, we have just seen and is called Construction function and adds the this, when call with new keyword.

We will go through the Method#4 in the next part. You can find part-2 here.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store