2

I have a function that I attach to a dom object. I want to be able to reference the dom object from within the function, but when I call it from an event, this isn't equal to the right thing.

var main = document.getElementById('main');

main.testFunction = () => {
  console.log('this',this);
}

main.addEventListener('click', main.testFunction);

Instead it's equal to window. Why is this? How do I reference the object that the method is part of?

stackers
  • 2,701
  • 4
  • 34
  • 66
  • 2
    Do not use the function arrow expression, they work _without its own bindings to the this, arguments, super, or new.target keywords_, change your expresion to `main.testFunction = function() {...}` and it will work as you expect. – Shidersz Apr 21 '19 at 18:48

1 Answers1

4

This is because you are using arrow function. Arrow function doesnot have their own this. Use normal function it will work. According to MDN

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this

var main = document.getElementById('main');
main.testFunction = function() {
  console.log('this',this);
}
main.addEventListener('click', main.testFunction);
<button id="main"> main</button>

Secondly when you use addEventListener and pass the function then the element to which event is attached is automatically binded to given function.See the snippet

var main = document.getElementById('main');
function testFunction(){
  console.log('this',this);
}
main.addEventListener('click', testFunction);
<button id="main"> main</button>

If you want to access the element inside arrow function use event.target instead of this

var main = document.getElementById('main');
main.testFunction = (e) => {
  console.log('this',e.target);
}
main.addEventListener('click', main.testFunction);
<button id="main"> main</button>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Seems my actual problem was passing the function as an argument, so thanks for the detailed answer. – stackers Apr 21 '19 at 18:56