Home > Web Front-end > JS Tutorial > How Does the `new` Operator in JavaScript Create Objects and Establish Their Inheritance?

How Does the `new` Operator in JavaScript Create Objects and Establish Their Inheritance?

Linda Hamilton
Release: 2024-10-27 01:46:30
Original
740 people have browsed it

How Does the `new` Operator in JavaScript Create Objects and Establish Their Inheritance?

Demystifying the Inner Workings of the new Operator in JavaScript

The misunderstood terrain of JavaScript, akin to the prototype chain, unveils a fundamental query: how does the "new" operator orchestrate object creation, defining their lineage and core attributes?

The Essence of new

To unravel this enigma, consider an alternative illustration:

function NEW(f) {
  var obj, ret, proto;

  // Examine `f.prototype`
  proto = Object(f.prototype) === f.prototype ? f.prototype : Object.prototype;

  // Inherit from `proto`
  obj = Object.create(proto);

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

  // Determine return type
  if (Object(ret) === ret) { // Object returned?
    return ret;
  }

  // Otherwise, return inherited object
  return obj;
}
Copy after login

Understanding the Mechanism

The new operator relies on the internal [[Construct]] mechanism, which:

  1. Creates a native object.
  2. Sets its [[Prototype]] to the function's prototype or Object.prototype (if the prototype is primitive).
  3. Invokes the function with the object as "this."
  4. Returns the object internally created if the function returns a primitive, or the object returned by the function if it returns an object.

Practical Application

Illustrating the power of this concept:

function Foo(arg) {
  this.prop = arg;
}
Foo.prototype.inherited = 'baz';

var obj = NEW(Foo, 'bar');
Copy after login

This creates an object inheriting from Foo, with "inherited" inherited property, and "prop" property with value "bar."

The above is the detailed content of How Does the `new` Operator in JavaScript Create Objects and Establish Their Inheritance?. 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