Pop
Pop

Reputation: 145

Confusion with process of creation an object when we use new keyword

I was learning JS and slightly confused with what happens behind the scenes with creation an object with new keyword. As I found out, three things basically happen when we use new keyword:

  1. A new empty object is created and assigned to this.
  2. The function body executes. Usually it modifies this, adds new properties to it.
  3. The value of this is returned.

Look, in the step two when function body executes, Does it run all of the body code and puts all functions and properties having "this" into object which was created in step 1? I mean, what is the reason of running the function body in step 2. Here is the sample code:

function PageState(){
  let currentState = new homeState();

  this.change = function(state){
    currentState=state;
  }
}

const page = new PageState();

function homeState(){
  document.querySelector('.div').style.width = "100px";
}

Upvotes: -1

Views: 63

Answers (1)

JasonB
JasonB

Reputation: 6368

In this code snippet, step 1 happens automatically, then I assign some members (properties or methods) to this which is step 2, then step 3, this is returned.

Calling const object1 = new MyObject() means create an object with greeting set to 'Hi', name set to 'Tim', and getMessage set to a function that returns the concatenated message; then assign that object to object1.

You can create a new instance of MyObject by calling const object2 = new MyObject(); and that time the function runs, there is a new this.

You can modify your objects without affecting the original function/object used to create the others.

function MyObject() {
  this.greeting = 'Hi';
  this.name = 'Tim';
  this.getMessage = function() {
    return this.greeting + ' ' + this.name + '!';
  }
}

const object1 = new MyObject();
const object2 = new MyObject();
object2.greeting = 'Yo';
object2.name = 'Sam';
const object3 = new MyObject();

console.log( object1.getMessage() );
console.log( object2.getMessage() );
console.log( object3.getMessage() );

Upvotes: 1

Related Questions