Simplifying the 'new' Keyword!
So, this week I'm gonna be breaking down another essential Javascript operator to become familiar with: the new
operator. I think that the best way to start off an explanation of new
is by first describing what happens when it is used.
Four things happen when new
is used:
- A new, empty object is created.
-
this
is bound to the new object. - The newly created object's internal
[[prototype]]
, or__proto__
, is set to be the same as the[[prototype]]
of the constructor function's. - The new object is returned with a
return
this
at the end of the function.
I know that might not make much sense!
Let's create a really simple constructor function so we can get a more practical idea of how new
works. This one I'm going to call Homie
and it's going to take in a couple of parameters and set them to the value of this
.
const Homie = function (name, thingInCommon, isChill, likesMyJokes) {
this.name = name;
this.thingInCommon = thingInCommon;
this.isChill = isChill;
this.likesMyJokes = likesMyJokes;
}
Now we can use new
to invoke the constructor:
const homie1 = new Homie ('Sweaty Steve', 'Weightlifting', false, true);
So in this example, we have:
- Created an object, called 'homie1', that seems like a decent gym buddy. You probably wouldn't want to hang out with Sweaty Steve in your spare time, but he seems like he'd give you tips about your form and spot you if you needed him to.
- Bound
this
to homie1. - Added a
__proto__
to homie1 that will point to ourHomie.prototype
. - Returned our homie1 object.
We can see this in action with a quick console log:
console.log(homie1)
/* Homie {name: "Sweaty Steve", thingInCommon: "Weightlifting", isChill: false, likesMyJokes: true}
isChill: false
likesMyJokes: true
name: "Sweaty Steve"
thingInCommon: "Weightlifting"
__proto__: Object */
The commented code is what I get back when running all of the prior code in a Google Chrome console window. So we can clearly see that an object has been created with all of the values that we input when we called the new
keyword. We can also see the __proto__
object, which I will dive further into in a future post.
We could continue using the new
keyword and passing in new parameters to quickly create a whole gang of homies to kick it with!
I hope this gives a small example of how new
can be used to quickly create new objects from a constructor function and some of the properties that carry over to these objects.
Top comments (0)