Home > Web Front-end > JS Tutorial > How does the `new` operator work behind the scenes to create and initialize objects in JavaScript?

How does the `new` operator work behind the scenes to create and initialize objects in JavaScript?

Patricia Arquette
Release: 2024-10-29 03:21:02
Original
555 people have browsed it

How does the `new` operator work behind the scenes to create and initialize objects in JavaScript?

How the new Operator Creates and Initializes Objects in JavaScript

The new operator is a powerful keyword in JavaScript used to create new objects. It plays a crucial role in object-oriented programming but can be challenging to understand fully, particularly in relation to the prototype chain.

Understanding the new Operator

When using the new operator with a function, the following steps occur internally:

  1. A new native object is created.
  2. The internal [[Prototype]] property of the object is set to the function's prototype property.
  3. The function is called with the newly created object as its this value.
  4. If the function returns a primitive value, the internally created object is returned.
  5. Otherwise, if the function returns an object, the internally created object is abandoned.

An Example Implementation

To demonstrate the functionality of the new operator, here's an equivalent implementation:

<code class="javascript">function NEW(f) {
  let obj, ret, proto;

  // Check if `f.prototype` is an object
  proto = f.prototype ? f.prototype : Object.prototype;

  // Create an object inheriting from `proto`
  obj = Object.create(proto);

  // Call the function with `obj` as `this`
  ret = f.apply(obj, Array.prototype.slice.call(arguments, 1));

  // Return the object from the function or the newly created `obj`
  return Object(ret) === ret ? ret : obj;
}</code>
Copy after login

Example Usage

Consider this example:

<code class="javascript">function Foo(arg) {
  this.prop = arg;
}
Foo.prototype.inherited = 'baz';

let obj = NEW(Foo, 'bar');
console.log(obj.prop); // Output: "bar"
console.log(obj.inherited); // Output: "baz"
console.log(obj instanceof Foo); // Output: true</code>
Copy after login

This demonstrates how the new operator creates an object that inherits from the function's prototype, and allows access to its properties and methods.

The above is the detailed content of How does the `new` operator work behind the scenes to create and initialize objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template