Home >Web Front-end >JS Tutorial >What Does the 'new' Keyword do in JavaScript under the hood?
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 thing new 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;
ConstructorFunction.call(obj);
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.
The above is the detailed content of What Does the 'new' Keyword do in JavaScript under the hood?. For more information, please follow other related articles on the PHP Chinese website!