Demystifying Object Instantiation with JavaScript's "new" Operator

2024-07-27

  1. Empty Object Built: When you use new with a constructor function, JavaScript creates a brand new, empty object.
  2. 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.
  3. this اشاره (zhǐshǒu - pointer) Set: Inside the constructor function, the this 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.
  4. 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



Enhancing Textarea Usability: The Art of Auto-sizing

We'll create a container element, typically a <div>, to hold the actual <textarea> element and another hidden <div>. This hidden element will be used to mirror the content of the textarea...


Alternative Methods for Validating Decimal Numbers in JavaScript

Understanding IsNumeric()In JavaScript, the isNaN() function is a built-in method used to determine if a given value is a number or not...


Alternative Methods for Escaping HTML Strings in jQuery

Understanding HTML Escaping:HTML escaping is a crucial practice to prevent malicious code injection attacks, such as cross-site scripting (XSS)...


Learning jQuery: Where to Start and Why You Might Ask

JavaScript: This is a programming language used to create interactive elements on web pages.jQuery: This is a library built on top of JavaScript...


Alternative Methods for Detecting Undefined Object Properties

Understanding the Problem: In JavaScript, objects can have properties. If you try to access a property that doesn't exist...



javascript new operator

Unveiling Website Fonts: Techniques for Developers and Designers

The most reliable method is using your browser's developer tools. Here's a general process (specific keys might differ slightly):


Ensuring a Smooth User Experience: Best Practices for Popups in JavaScript

Browsers have built-in popup blockers to prevent annoying ads or malicious windows from automatically opening.This can conflict with legitimate popups your website might use


Interactive Backgrounds with JavaScript: A Guide to Changing Colors on the Fly

Provides the structure and content of a web page.You create elements like <div>, <p>, etc. , to define different sections of your page


Understanding the Code Examples for JavaScript Object Length

Understanding the ConceptUnlike arrays which have a built-in length property, JavaScript objects don't directly provide a length property


Choosing the Right Tool for the Job: Graph Visualization Options in JavaScript

These libraries empower you to create interactive and informative visualizations of graphs (networks of nodes connected by edges) in web browsers