Home >Web Front-end >JS Tutorial >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; }
Understanding the Mechanism
The new operator relies on the internal [[Construct]] mechanism, which:
Practical Application
Illustrating the power of this concept:
function Foo(arg) { this.prop = arg; } Foo.prototype.inherited = 'baz'; var obj = NEW(Foo, 'bar');
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!