-2

Code here:

const a = {
  target: 'a',
  getTarget: () => {
    setTimeout(() => {
      console.log(this.target)
    }, 1000)
  },
}
window.target = 'window';
a.getTarget();

I thought it will print 'a', but it turns out to be 'window'.

MauriceNino
  • 4,927
  • 1
  • 14
  • 44
innocentDrifter
  • 845
  • 1
  • 5
  • 16

1 Answers1

2

This is because of the first arrow function you use:

const a = {
  target: 'a',
  getTarget(){
    setTimeout(() => {
      console.log(this.target)
    }, 1000)
  },
}
window.target = 'window';
a.getTarget();// a
8HoLoN
  • 970
  • 1
  • 12