In JavaScript, the 'new' keyword creates a new instance of an object from a constructor function.
When you use the new keyword with a constructor function, the following steps are executed:
Here's a concise code example that demonstrates the use of the new keyword in JavaScript, covering all the essential steps involved in object creation, prototype linkage, and binding 'this'.
// Step 1: Define a constructor function function Car(make, model) { this.make = make; // Step 3: Bind properties to the new object this.model = model; } // Step 4: Add a method to the Car prototype Car.prototype.getDetails = function() { return `${this.make} ${this.model}`; }; // Step 2: Create a new instance of Car using the new keyword const myCar = new Car('Toyota', 'Corolla'); // Using the method from the prototype console.log(myCar.getDetails()); // Output: Toyota Corolla // To demonstrate the prototype linkage console.log(myCar instanceof Car); // Output: true
In summary, the new keyword is essential for object-oriented programming in JavaScript. It enables the creation of new instances of objects, establishes prototype inheritance, binds the context of this, and handles the return of the created object. Understanding how new works is crucial for effectively using constructor functions and classes in JavaScript.
The above is the detailed content of new keyword. For more information, please follow other related articles on the PHP Chinese website!