0

I am cofused about the behaviour of arrow functions. Please look at the following example:

class Test {
  foo2 = () => {
    console.log(this)
  }
}
let t1 = new Test

let Test2 = {
  foo2: () => {
    console.log(this)
  }
}

t1.foo2()
Test2.foo2()

Test2.foo2() returns an empty object which makes sense as arrow functions doesn't have there own "this", but why is t1.foo2() logging t1 object? Aren't both the situations same ?

user123456789
  • 424
  • 4
  • 15
  • _“When a class is evaluated, [for] each ClassElement [e.g. a field]: if a field is static, then `this` refers to the class itself; if a field is not static, then `this` refers to the instance.”_ — From the linked post. This means, `this` refers to the same thing in your arrow functions as in `class { foo2 = this }`, and for object literals (also mentioned in the linked post at the end of the “Function properties” subsection), as in `{ foo2: this }`. – Sebastian Simon Dec 29 '21 at 10:26
  • @sebastiansimon - It's not trivial to find the answer to this specific question in that duplicate. Can you provide a more direct pointer to where this precise question is answered there? Marking as a duplicate is kind of pointless without a precise pointer to what in the duplicate is the relevant part. That's like throwing a text book at someone and telling them to read it - it doesn't answer the question. – jfriend00 Dec 29 '21 at 10:26
  • @Emiel `class` doesn't create a "scope", it's just syntactic sugar for a bunch of things. The important one is this here: https://stackoverflow.com/a/48920356/476 – deceze Dec 29 '21 at 10:27
  • @jfriend00 Isn’t my comment enough? – Sebastian Simon Dec 29 '21 at 10:29
  • That works, I guess - it would be better if you explained exactly where in that long set of answers to go to read the relevant part. And your comment wasn't there when you marked it as a duplicate or when I wrote my comment. – jfriend00 Dec 29 '21 at 10:33
  • “When a class is evaluated, [for] each ClassElement [e.g. a field]: if a field is static, then this refers to the class itself; if a field is not static, then this refers to the instance.”  Would this be applied to both regular and arrow functions ? – user123456789 Dec 29 '21 at 11:26
  • 1
    The answer is really here: https://stackoverflow.com/a/48920356/476; an arrow function in a class is special syntactic sugar for a pattern often employed to avoid losing `this` context. – deceze Dec 29 '21 at 11:29
  • @deceze Thanks! Other answers may or may not be more accurete (I can't say), but as a beginner this makes sense to me. – user123456789 Dec 29 '21 at 11:42

0 Answers0