The new keyword
Shane Taylor (he/him)
Posted on May 19, 2019
Let's make use of some syntactical sugar - new
.
The new
keyword does a bunch of neat shit for us, but to fully appreciate what it does, we've gotta review something else real quick:
Functions in JavaScript are both objects and functions.
This means that this code actually works:
function sayHey() {
console.log('Heeeeey');
}
sayHey.target = 'Tang';
console.log(sayHey.target); // will log 'Tang' to the console
Cool!
So functions are both objects and functions - we can access the function bit with parentheses (sayHey()
) and we can access the object bit with dot notation (sayHey.something
).
The object portion of functions is always there and it always has a prototype key in it. And the value stored at the prototype key? It's a big ol' empty object and it's exactly where we want to store our functions.
Now we need to talk about the cool shit new
does for us in JavaScript. The new
keyword modifies the execution context of the function that immediately follows it by doing the following:
- It creates a property labeled
this
and assigns an empty object to that label - On the
this
object from above, the hidden property__proto__
is assigned the reference to the prototype property on the function being invoked - It returns the object stored at the
this
property as long as no object is returned from the function being invoked (h/t to Thomas Broyer for clarifying this point)
We would have to do all that stuff manually, but the new
keyword does all of that for us.
Finally, let's take a look at it in action:
function createCar(color, speed) {
this.color = color;
this.speed = speed;
}
createCar.prototype.go = function () {
console.log('I prefer to drive ' + this.speed + '.');
}
const myCar = new createCar('red', 'fast');
myCar.go(); // will log 'I prefer to drive fast.' to the console
console.log('myCar is', myCar.color); // will log 'myCar is red' to the console
Posted on May 19, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.