0

Why reference to this object's method works

const obj = {
  hi: () => alert('hi')
}
obj.hi() // 'hi'

const myMethod = obj.hi
myMethod() // 'hi'

But reference to the event's object method does not?

const link = document.querySelector('a')
link.addEventListener('click', (e) => {
  const doNotFollowLink = e.preventDefault
  doNotFollowLink()
  alert('this line was never reached')
})
<a href="https://google.com">Click here</a>
Anton Arbus
  • 61
  • 2
  • 6
  • read the error in the browser console – Jaromanda X Jul 11 '22 at 06:06
  • 1
    By putting the function to be called (like a callback) into its own variable: `const doNotFollowLink = e.preventDefault`, its calling context, or `this`, gets lost - `this` no longer refers to `e`. `preventDefault` needs to be called with a `this` of the event to work properly. – CertainPerformance Jul 11 '22 at 06:07
  • 1
    so `const doNotFollowLink = e.preventDefault.bind(e);` – Jaromanda X Jul 11 '22 at 06:07
  • @JaromandaX, browser console says: "Uncaught TypeError: Illegal invocation at HTMLAnchorElement." – Anton Arbus Jul 11 '22 at 06:14
  • @JaromandaX, your code with 'bind' works, thank you! – Anton Arbus Jul 11 '22 at 06:20
  • By the way, your browser issues unhelpful errors! another reason to develop using something that is not Chromium based :p – Jaromanda X Jul 11 '22 at 06:25
  • Explanation for myself, it seems e.preventDefault() uses THIS in its implementation and it is lost when we assign it to another variable const obj = { number: 5, showNumber: function() { alert(this.number) } } obj.showNumber() // 5 const myShowNumber = obj.showNumber myShowNumber() // undefined const myShowNumber2 = obj.showNumber.bind(obj) myShowNumber2() // 5 – Anton Arbus Jul 11 '22 at 08:04

0 Answers0