1
const input= document.querySelector('.search');

input.addEventListener('keyup', e=>{
  console.log(this.value);
});

This doesn't do what I expected, since I'm calling the event listener on the input. I figured 'this' would be the input, but instead it's referring to the window. I'm confused about why this is. If anyone can explain it that'd be great.

To solve this I created a function and passed it into the listener.

function value(){
  console.log(this.value)
}

input.addEventListener('keyup', value)

I'm still confused about why doing it this way allows 'this' to refer to the input.

karel
  • 5,489
  • 46
  • 45
  • 50
  • See https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch – Tiago Coelho Dec 11 '18 at 06:13

2 Answers2

3

An arrow function (() => {}) does not have its own dedicated context as this but inherits it from whatever scope it is defined in.

If you want to get the correct this then you need to define a "normal" function just like you did.

rorschach
  • 2,871
  • 1
  • 17
  • 20
2

You can't rebind this in arrow functions. With arrow function this is determined by lexical scoping (where the function was defined). You should use a regular function here:

const input= document.querySelector('.search');
 

// use a regular function and this will be what you expect
input.addEventListener('keyup', function(e){
  console.log(this.value);
});
<input class="search" />
Mark
  • 90,562
  • 7
  • 108
  • 148