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:
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>
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>
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!