SoFunction
Updated on 2025-04-12

Detailed explanation of the use of new operators in JavaScript

1. The role of new operator

1.1 Basic Concept

newOperators are used to create an instance object of a given constructor.

1.2 Basic examples

function Person(name, age) {
     = name;
     = age;
}

 = function() {
    (`Hello, I'm ${}`);
};

const person = new Person('Zhang San', 20);
(); // "Hello, I'm Zhang San"

2. The execution process of new operator

2.1 Four steps

  • Create a new object
  • Set up the prototype chain
  • Bind this and execute the constructor
  • Return result

2.2 Detailed process examples

function Person(name, age) {
     = name;
     = age;
    
    // Case 1: Return to the original value    return 123; // Will be ignored    
    // Case 2: Return object    // return { foo: 'bar' }; // will return the object normally}

// Steps Democonst person = new Person('Zhang San', 20);

// is equivalent to the following process:function newOperator(Constructor, ...args) {
    // 1. Create a new object and point its prototype to the constructor's prototype    const obj = ();
    
    // 2. Bind this and execute the constructor    const result = (obj, args);
    
    // 3. Judging by the return value    return result instanceof Object ? result : obj;
}

3. Analysis of special circumstances

3.1 The influence of the constructor return value

// Case 1: Return to the original valuefunction Test1() {
     = 1;
    return 'hello';
}
(new Test1()); // Test1 {foo: 1}

// Case 2: Return objectfunction Test2() {
     = 1;
    return {bar: 2};
}
(new Test2()); // {bar: 2}

3.2 Limitations of arrow functions

// Arrow function cannot be used as constructorconst Person = (name) => {
     = name;
};

// Error exampleconst person = new Person('Zhang San'); // TypeError

4. Handwriting implements new operator

4.1 Basic version

function myNew(Constructor, ...args) {
    // 1. Create a new object    const obj = {};
    
    // 2. Set up the prototype chain    obj.__proto__ = ;
    
    // 3. Bind this and execute the constructor    const result = (obj, args);
    
    // 4. Return result    return result instanceof Object ? result : obj;
}

4.2 Optimized Version

function myNew(Constructor, ...args) {
    if (typeof Constructor !== 'function') {
        throw new TypeError('Constructor must be a function');
    }
    
    // Use instead of __proto__    const obj = ();
    
    try {
        const result = (obj, args);
        return result instanceof Object ? result : obj;
    } catch (error) {
        // Handle constructor execution error        throw error;
    }
}

// Use examplefunction Person(name, age) {
     = name;
     = age;
}

const person = myNew(Person, 'Zhang San', 20);
(person); // Person {name: 'Zhang San', age: 20}

5. Practical application scenarios

5.1 Creating an object instance

// Create custom objectsfunction User(name, role) {
     = name;
     = role;
}

const admin = new User('admin', 'administrator');

// Built-in constructorconst date = new Date();
const regexp = new RegExp('\\w+');
const obj = new Object();

5.2 Implementing Inheritance

function Animal(name) {
     = name;
}

function Dog(name, breed) {
    // Call the parent class constructor    (this, name);
     = breed;
}

// Set up the prototype chain = ();
 = Dog;

const dog = new Dog('Benefit', 'Shiba Inu');

6. Interview FAQ

6.1 What is the principle of the new operator?

Answer: The new operator mainly completes the following tasks:

  • Create a new object
  • Point the prototype of the new object to the constructor's prototype
  • Bind this of the constructor to a new object
  • Judging the final return result based on the constructor return value

6.2 What is it?

function Person(name) {
    if (!) {
        throw new Error('The new operator must be called');
    }
     = name;
}

// Call correctlyconst person1 = new Person('Zhang San');

// Incorrect callconst person2 = Person('Zhang San'); // Error: Must be called using the new operator

6.3 How to ensure that the constructor is called correctly?

function Person(name) {
    if (!(this instanceof Person)) {
        return new Person(name);
    }
     = name;
}

// Both methods of calling are OKconst person1 = new Person('Zhang San');
const person2 = Person('Li Si');

7. Best Practice Suggestions

  • Constructor initial letter capitalize
  • Always call constructors using new
  • Not returning an object in the constructor
  • Check instances using instanceof
  • Preferred class syntax
// Recommended use of classclass Person {
    constructor(name) {
         = name;
    }
    
    sayHello() {
        (`Hello, ${}!`);
    }
}

// instead of constructorfunction Person(name) {
     = name;
}
 = function() {
    (`Hello, ${}!`);
};

Summarize

newOperators are an important part of JavaScript object-oriented programming. Understanding how it works not only helps us use it better, but also helps us better answer related questions in interviews. In actual development, it is recommended to use more modern onesclassSyntax to create classes and objects, but understandnewThe principle of operators is still important.

I hope this article can help you better understand JavaScriptnewOperator!

The above is the detailed explanation of the new operator in JavaScript. For more information about JavaScript new operators, please pay attention to my other related articles!