1

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();
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
youhana
  • 318
  • 2
  • 16
  • 2
    Possible duplicate of [How does the new operator work in JavaScript?](http://stackoverflow.com/questions/6750880/how-does-the-new-operator-work-in-javascript) – J. Titus May 08 '17 at 14:10
  • 1
    @J.Titus : I opened the pointed question and it didn't answer my question, if you revise the pointed question, you will find that it didn't briefly describe the step number 1 there as he wrote that the new will point to the newly object only and didn't write the steps clearly as described below. – youhana May 08 '17 at 14:15

1 Answers1

2

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();
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151