youhana
youhana

Reputation: 328

When a function is invoked with `new`, how can `this` in the body point to the newly-created object when it has not yet been assigned to a variable?

Kindly I am a beginner student in the JavaScript world, and I stopped studying on the point that the new keyword points to the newly created object, let's write some code and then ask my question.

function Employee(name) {
    this.name = name;
}

var x = new Employee("youhana");

How does new keyword forced this keyword to point to the x object despite the expression didn't reached the end, I mean

var x = new Employee("youhana");

Firstly, the = operand will wait to the end of the expression evaluation of new Employee("youhana"); to be ended, then it will assign the final value of this expression and put it to x which will be object, another example:

function Book(){
  /* at this point, there's is no relation between
   * the new object that will be created after this
   * block of code ended, so how new keyword in this
   * point knew that the new object **will** be obj
   * and **this** will point to it?
   */
}

var obj = new Book();

Upvotes: 1

Views: 63

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138234

Order of the new expression:

1) a new empty Object is created using Constructor.prototype as prototype

x=Object.create(Employee.prototype);

2)The constructor is called, binding the new Object as this:

Employee.call(x);

3)the expression returns

function new_obj(of){
  var obj=Object.create(of.prototype);
  of.call(obj);
  return obj;
}

var x=new_obj(Employee);
//equals
var x=new Employee();

Upvotes: 3

Related Questions