To create a new instance of Person, you must use the new operator. Calling the constructor in this way actually goes through four steps: (1) Create a new object; (2) Assign the scope of the constructor to the new object (thus this refers to the new object); (3) Execute the code in the constructor (add attributes to the new object); (4) Return a new object.

New operator

With the introduction of the basic concepts above, and the addition of the new operator, we can create objects in the traditional object-oriented class + new way, which in JavaScript we call Pseudoclassical. Based on the example above, we execute the following code

var obj = new Base();

What is the result of such code? The object model we see in Javascript engines is:

What exactly does the new operator do? It’s really simple. It does three things.

var obj = {};
obj.__proto__ = Base.prototype;
Base.call(obj);

On line 1, we create an empty object called obj. On line 2, we refer the __proto__ member to the Base object. On line 3, we replace the this pointer to the Base object with obj. So we assign an ID member variable to the obj object with the value “base” for the use of the call function.

What if we added some functions to the Base. Prototype object? For example:

Base.prototype.toString = function() {
return this.id;
}

So when we use new to create a new object, the toString method can also be accessed as a method of the new object, according to __proto__’s nature. Constructor sets the member variables of ‘class’ (for example, id) and constructor sets the public methods of ‘class’ (prototype). Classes and class instantiation are then simulated using function objects and Javascript’s unique __proto__ and Prototype members and new operators.

Note: This article is reproduced [The article links]