Understanding the 'new' Keyword in JavaScript
The concept of using 'new' in JavaScript can be perplexing, especially when considering JavaScript's non-object-oriented nature. To clarify, 'new' operates in the following ways:
1. Creating a New Object:
- It establishes a new object, which is fundamentally an object of the type "object."
2. Setting the Prototype:
- It associates the newly created object's inaccessible [[prototype]] property with the external prototype property of the constructor function. This inheritance relationship enables access to properties defined in the constructor's prototype.
3. Binding the 'this' Variable:
- It designates the 'this' variable to point to the newly created object, allowing for explicit access to its properties and methods within the constructor function.
4. Executing the Constructor:
- It runs the constructor function, using the newly created object as the context for 'this.'
5. Returning the Object:
- After execution, it returns the newly created object unless the constructor explicitly returns a different object.
Utilizing the 'new' Keyword:
- The appropriate scenario for using 'new' is when instantiating objects, usually when creating classes or simulating object-oriented behavior.
- It's not applicable when manually creating objects using object literals or hypothetical constructs.
Example:
function Constructor() {
this.property = "value";
}
const object = new Constructor();
console.log(object.property); // "value"
Copy after login
Prototype Chain:
- Objects created with 'new' have a prototype chain.
- The [[prototype]] property of the sub-object's prototype points to the prototype property of the base constructor function.
- This chain allows for accessing inherited properties defined in the base constructor's prototype.
The above is the detailed content of How Does the `new` Keyword Work in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!