Demystifying Object Instantiation with JavaScript's "new" Operator
- Empty Object Built: When you use
new
with a constructor function, JavaScript creates a brand new, empty object. - Prototype Linked: The
new
keyword then connects this new object to the constructor function's prototype. This prototype acts like a mold that the new object inherits properties and methods from. this
اشاره (zhǐshǒu - pointer) Set: Inside the constructor function, thethis
keyword is special. It refers to the new object being created. This allows the constructor function to set properties and methods on the new object.- Possible Return Value: The
new
keyword itself doesn't necessarily return anything, but the constructor function can return a value to assign to the new object.
Think of new
like an instruction to the JavaScript engine to use a constructor function as a template to build a new object, following these steps.
Here's an example:
function Car(model, year) {
this.model = model; // Sets the model property on the new object
this.year = year;
}
const myCar = new Car("Camry", 2020);
console.log(myCar); // {model: "Camry", year: 2020}
In this example, the new Car
part uses the Car
constructor function as a blueprint to create a new object myCar
. The Car
function then sets properties (model
and year
) on myCar
.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
// Method to display car information
this.getInfo = function() {
return `Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`;
}
}
const car1 = new Car("Toyota", "Camry", 2023);
const car2 = new Car("Ford", "Mustang", 2022);
console.log(car1.getInfo()); // Output: Make: Toyota, Model: Camry, Year: 2023
console.log(car2.getInfo()); // Output: Make: Ford, Model: Mustang, Year: 2022
This example creates a Car
constructor that takes three arguments (make
, model
, and year
) and assigns them as properties to the new object. It also defines a getInfo
method to display car information. The new
keyword is used with Car
to create two car objects, car1
and car2
.
Using Prototype for Shared Properties:
function User(name, email) {
this.name = name;
this.email = email;
}
// Define a method on the prototype for all User objects
User.prototype.login = function() {
console.log(`${this.name} has logged in.`);
}
const user1 = new User("Alice", "[email protected]");
const user2 = new User("Bob", "[email protected]");
user1.login(); // Output: Alice has logged in.
user2.login(); // Output: Bob has logged in.
This example shows how the prototype can be used to define shared methods for all objects created with the User
constructor. The login
method is defined on the User.prototype
object, and any User
object can access it.
Custom Return Value from Constructor:
function Point(x, y) {
// Instead of directly assigning properties, we can return a new object
return {
x: x,
y: y,
// Method to get distance from origin
getDistance: function() {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
}
}
}
const point1 = new Point(3, 4);
console.log(point1.getDistance()); // Output: 5
This example demonstrates how a constructor function can return a new object with its own properties and methods. This approach allows for more flexibility in defining object structure.
This is a simpler way to define objects directly without a constructor function. You use curly braces {}
to specify key-value pairs for the object's properties.
const person = {
firstName: "John",
lastName: "Doe",
greet: function() {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
}
};
person.greet(); // Output: Hello, my name is John Doe
This approach is useful for creating simple objects without complex logic or inheritance. However, it doesn't involve linking to a prototype or using this
within methods.
Object.create() Method:
This method allows you to create a new object that inherits properties from an existing object. It takes two arguments:
- Prototype: The object to inherit properties from.
- Properties Object (Optional): An object defining additional properties for the new object.
const personPrototype = {
greet: function() {
console.log("Hello from the prototype!");
}
};
const employee = Object.create(personPrototype);
employee.name = "Alice";
employee.greet(); // Output: Hello from the prototype!
// You can add additional properties to the new object
employee.work = "Software Engineer";
console.log(employee); // { name: "Alice", work: "Software Engineer" }
Here, employee
inherits the greet
method from personPrototype
. This method is useful for creating objects with a specific inheritance pattern.
Choosing the Right Method:
- Use
new
with constructor functions when you need object creation with inheritance, property initialization, and potential custom return values. - Use object literal syntax for simple objects without complex logic or inheritance.
- Use
Object.create()
when you need to create objects with specific inheritance patterns.
javascript new-operator