Previously we had seen JavaScript's Object Literal method of creating an object. In this post, we will explore how to create an object using the Constructor Function. Yes, that's right. You can create an object using a function!
For those of you familiar with Classes and instantiating an object from a class, this concept is very similar.
Then why don't we just create a class??
Surprisingly, classes were introduced in JS only with ES6 (ECMAScript2015), which is quite recent. Sigh! Until then, Constructor Function was our savior. (Don't worry if you don't know what I am talking about.)
Having said that, let's dive in:
We will use the same object format we used in #1 post for our example. Here it is,
function Person(thename) {
this.name = thename;
this.greeting = function() {
console.log('Hola! Mi nombre es ' + this.name + '.');
}
}
PS. I have dropped the age and country attributes just to keep it simple.
This creates a function "object" with a namespace Person, within which there are two attributes called name (of string type) and greeting (of function type).
Internally, JS converts this code into an Immediately-Invoked Function Expression and allocates a variable Person of type - function object. We will learn about IIFE later, let's keep it simple for now.
Note- The CAPITAL 'P' used while declaring 'Person' is nothing but a common naming convention for anything that resembles a Class. If you are using any modern code editor like VSCode with ES6 JS version, you will notice a warning like:
"This constructor function may be converted to a class declaration."
Remember, we haven't created an object yet. We have only defined what the object should look like. Now, to create an object, simply call the function like a constructor:
person1 = new Person('Sanchez');
This creates a new object called person1
. Go ahead and print person1 in your console using console.log(person1)
and dissect it. Open it until you have reached trivia. You will see something like this (and a lot more):
/**
* {
* name: 'Sanchez',
* greeting: f (), --> no name to the function - anonymous function
* __proto__: {
* constructor: f Person(thename), --> name of the function "Person"
* __proto__: Object
* }
* }
*/
What is actually happening here?
We can break it down to three steps:
-
new creates a new empty object and assigns it to this ->
this = {}
- The function then runs and adds new key-value pairs to this object ->
this.name = thename
andthis.greeting = function() {...}
- Finally, the value of this is returned and assigned to person1 ->
person1 = function () {... return this; }
Note- In this case, your constructor function should NOT have any return statement. JS won't stop you from adding one. If you do, that return statement will be executed and the corresponding object will be returned instead of this and the instantiation will work differently than you anticipate. So be careful!
But what is this ugly wormy thing that creeped into your object called __proto__
!! This is JavaScript's Object Prototypes. It's an amazing and equally important concept for us to master Objects in JS. We will get to them soon!
For now, stash them in your memory palace.
When do we use Constructor Functions?
Take a scenario where you just know you are going to have Objects of 'Person' type, but don't know HOW MANY. Here, it is simply convenient to call var newguy = new Person('His Name')
everytime you encounter a need for new object, instead of creating them using the verbose method of Object Literal.
But this can't be all so perfect, can it?
Think about this...
Everytime you create a new object from Person, a new variable is getting assigned in the memory with an object reference. And EVERY object contains a function called greeting which is essentially doing the same thing in all the objects. If you have 10 such object, 50... 100... How many times do we define the same function for every object!!
We have solution to this extravagant waste of space. πΆπ΅ #SuspenseMusic ...
Prototypes.
Whaaaaaa.... π±
Anyways, let's not overload ourselves. If you have made it this far, treat yourself with some π¦. Take a break. Then move on to #3.
PS: Before you move on to the next chapter. I would suggest you play around with this a bit. Create new functions. Instantiate new objects. Open them up. Open what's openable inside of them. Keep going. I promise, it's fun! Comment here some interesting things you see.
Also, I will soon add some JS Interview kind of questions to help you grasp the usage of these concepts soon. Hang in there!
Reference:
https://javascript.info/constructor-new#constructor-function
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
Top comments (0)