Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow function and this inside a constructor function

I have read this paragraph about the this keyword : https://bonsaiden.github.io/JavaScript-Garden/#function.this

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)
    }
console.log(obj);
obj.foo()

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

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

var obj = new bar()
console.log(obj);
obj.foo()

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 ?

like image 456
Pierre Capo Avatar asked Oct 24 '25 02:10

Pierre Capo


1 Answers

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.

like image 70
Ele Avatar answered Oct 26 '25 19:10

Ele