0

Everywhere I read people say "this" inside a function is the global object, "this" outside a function is the module.exports, and "this" inside an arrow function is an empty object.

But it's not exactly like that inside an instanced function, is it? For example:

function Test() {
    this.arrowThis = () => {
        console.log(this)
    }

    console.log(this)
}

const test = new Test
console.log(test.arrowThis())

When the function is being instanced the "this" output is the function itself and when the .arrowThis() arrow function is being called the output are 2 values, one value is the instanced function and the other is an empty object.

I am having dificulties to understand the logic behind it. Could anyone here try to explain exactly what is the behavior of "this" in this case?

  • Both `this` refer to the instance `test`. Arrow functions do not have their own `this` binding. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – evolutionxbox Sep 19 '22 at 20:01
  • "*Everywhere I read people say …*" - you seem to be reading in the wrong places. Can you link your sources? – Bergi Sep 19 '22 at 20:14
  • "*When the function is being instanced the "this" output is the function itself*" - no. It's the `test` instance, not the `Test` function. "*the output are 2 values, one value is the instanced function and the other is an empty object.*" - no. The second value is `undefined`, the return value of the `test.arrowThis()` call. – Bergi Sep 19 '22 at 20:16
  • Thanks for clarifying that part, I am new to programing and I am trying to understand the "this" logic. Why is 2 values coming as output though, the instanced object plus the undefined value. – Lucas Gomes Sep 19 '22 at 20:32
  • Well there's 3 `console.log` calls in your code, that's why you get 3 outputs… – Bergi Sep 19 '22 at 22:38

0 Answers0