How the new Keyword Works in JavaScript

The new keyword in JavaScript is used to create an instance (object) from a constructor function.

Basic Example

    function MyFunc() {
    this.x = 100;
    }

    var obj1 = new MyFunc();
    console.log(obj1.x); // 100

Here, MyFunc is a constructor function. obj1 is an instance created using new.

What Does new Do?

  1. Create an empty object: {}
  2. Set the object's prototype: obj.__proto__ = MyFunc.prototype
  3. Bind this to the new object: Inside the constructor, this refers to the new object.
  4. Return the object: If not explicitly returned, this is returned automatically.

Example with prototype

    function MyFunc() {
    var myVar = 1;
    this.x = 100;
    }

    MyFunc.prototype.y = 200;

    var obj1 = new MyFunc();

    console.log(obj1.x); // 100
    console.log(obj1.y); // 200

myVar is not accessible because it's not attached using thisx is part of the new object, and y is inherited through the prototype.

Special Cases

Returning a Primitive

    function MyFunc() {
    this.x = 100;
    return 200;
    }

    var obj = new MyFunc();
    console.log(obj.x); // 100

Here, return 200; is ignored because it's a primitive value.

Returning a Custom Object

    function MyFunc() {
    this.x = 100;
    return { a: 123 };
    }

    var obj = new MyFunc();
    console.log(obj.x); // undefined
    console.log(obj.a); // 123

In this case, the custom object is returned, so this.x is not part of the result.

Summary

  • The new keyword creates and returns an object.
  • It links the object to the constructor’s prototype.
  • It binds this to the new object.
  • If a custom object is returned, it overrides the default return.