Arrow function and this inside a constructor function

549 views javascript

I have read this paragraph about the this keyword :

In this first case this refers to global objet, and it seems totally normal because when we have an arrow function, it automatically bind this with the one in the outer scope.

var obj = {
      foo : () => console.log(this)

However, I'm not able to explain the following behavior :

function bar(){ = () => console.log(this)

var obj = new bar()

Now, this refers to obj instead of global. Why is that ? It seems to me that using the new keyword with the constructor function should return an object obj which is exactly identical as the one in the first example. And so the arrow function should have a this which refers to global and not to obj. Could you explain to me what's happening in the second case please ?

answered question

Whenever ES6+ confuses me, I look at a transpiled ES6->ES5 version of the code to understand it

2 Answers


Although I myself am far from good with objects (need to work on that), I think that when you do const test = new Test() you initialize a new object. That way, the scope(?) of this references only to the newly created object, thus why you do and later on you reference to that foo property by using On the other hand, when you just do const obj = { .... }, you don't actually initialize a new object, so the this goes straight to the global object - the window. So, const test = new Test creates a new object, while using only const obj = {} is not a new object and this by default goes to the window object.

posted this

Functions -> No separate this

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming

Read more about the new keyword here

The constructor function ... is called with the specified arguments, and with this bound to the newly created object.

The bar() constructor defines this as itself.

posted this

Have an answer?


Please login first before posting an answer.