Mukund Kumar
Mukund Kumar

Reputation: 23191

How Arrow function work inside constructor?

I am bit confuse about arrow function inside constructor.

As per my knowledge: If we will use arrow function, the keyword this will not rebound to that actual function. it is inherited from the parent scope.

let's take example:

var d = {
  b: 'b',
  x: () =>{
    console.log(this); // this will return Window Object.
 }
}
d.x();

it will print Window Object. that is fine.

But in constructor function

function A(){
  this.b ='b';
  this.x = () =>{
    console.log(this);
  }
}
var c = new A()
c.x();

this print object c. but according to me it should return Window Object. Why ?

Upvotes: 0

Views: 113

Answers (1)

idmean
idmean

Reputation: 14865

In the constructor this refers to the object on construction. Why else could you do this.b ='b';?

Since an arrow-function simply captures the current context, it captures the object in the constructor.

Upvotes: 1

Related Questions