0

First Question: Why is the value for this in getXArrow() equal to the Solution object? Shouldn't it equal the this value of the solution object which called it, which would be the Window object?

Second Question: Shouldn't the JS Engine travel up the scope chain of each function to find the value of x? The scope of getX() and getXArrow() don't have x, so the JS engine would check their caller (the Solution object) and find x: 10, as declared in the constructor. Instead, it seems to jump up to the global scope?

let x = 5
class Solution {
    constructor() {
        this.x = 10
    }
    getX() {
        console.log(this); 
        console.log(x); 
    }
    getXArrow = () => {
        console.log(this); 
        console.log(x); 
    }
}

s.getXArrow() // Output: Solution
              //         5
s.getX()      // Output: Solution
              //         5

Thank you!

Y. Moondhra
  • 195
  • 2
  • 12
  • 1
    A class method's `this` is the instance object itself, by default. class members are not hoisted into the lexical scope like they are in other langs; you have to use `this.x` to reach _that_ `x` – dandavis Jul 24 '19 at 17:28
  • 2
    JS has lexical scope, it doesn't matter who the caller is. There is only one `x` variable in your script anyway - a property is not a variable. – Bergi Jul 24 '19 at 17:46
  • Please ask a single question per post only. Btw, your first question can be easily researched by looking for how arrow functions work. – Bergi Jul 24 '19 at 17:47

1 Answers1

1

getX just has two scopes accessible: It's own function scope and the global scope. Classes don't create a scope, and thus x cannot be accessed. You do however have access to the instance via this and can access its .x property.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151