Home >Web Front-end >JS Tutorial >What Does the 'new' Keyword do in JavaScript under the hood?

What Does the 'new' Keyword do in JavaScript under the hood?

DDD
DDDOriginal
2025-01-05 12:56:39269browse

What Does the

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?

  1. 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.

  2. 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;
  1. 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);
  1. 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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Duplicate Value removeNext article:Duplicate Value remove