DEV Community

Discussion on: How to access “this” from inside a callback

Collapse
 
marklai1998 profile image
Mark Lai

I use arrow function 100% of time
I think that is much cleaner
Plus I can't think any reason to scope this inside a function (just don't make sense to me, scope in class maybe)

Collapse
 
reegodev profile image
Matteo Rigon • Edited

Actually there are cases where you want to have the inner scope rather then the outer:


const obj = {
  x: 10,
  foo() {
      return {
        x: 20,
        printX() {
          console.log(this.x); // prints 20
        }
      }
  },
  bar() {
      return {
        x: 20,
        printX: () => console.log(this.x) // prints 10
      }
  },
}

Collapse
 
marklai1998 profile image
Mark Lai

Sorry, this pattern is just worse, really worse
Hope you won't type this in real world

Collapse
 
logicmason profile image
Mark