Let’s talk about the new
keyword in JavaScript. It’s like the magic wand that makes constructor functions do their thing. But what’s really going on behind the scenes?
Pulls Out a Fresh Object
The first thingnew
does is whip up a shiny, empty object. Think of it as a blank canvas waiting to be painted on.Links It Up
That blank object? It gets hooked up to the prototype of the constructor function. Now it knows who its “parent” is, like getting added to a cool family tree.
obj.__proto__ = ConstructorFunction.prototype;
-
Hands Over the Keys
Inside the constructor,
this
becomes the new object. You can now slap on some properties and methods like you’re decorating your new room.
ConstructorFunction.call(obj);
- Goes With the Flow Finally, it checks if your constructor is returning something specific. If not, it shrugs and hands back the new object it made earlier.
Example time:
function Animal(type) {
this.type = type;
}
const cat = new Animal('cat');
console.log(cat.type); // cat
Without new
, all this cool stuff doesn’t happen—this
points to the wrong place, and the prototype chain? Totally busted. So yeah, new
is like your friendly helper, making sure everything runs smoothly when you’re building stuff.
Top comments (0)