Sławek Kabik
Sławek Kabik

Reputation: 699

Why is `this` binded to window?

I need to get a href value after click. My code looks like this:

$('.menu a').click (event) =>
  event.preventDefault()
  console.log($(this).attr('href')) # it returns 'undefined'

What am I doing wrong?

[edited]

My html code:

<div class="menu">
    <a href="/all/">All</a>
</div>

Upvotes: 1

Views: 39

Answers (1)

edi9999
edi9999

Reputation: 20554

This is because of the subtle difference in Coffeescript between => and ->

In JavaScript, the this keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of this will be lost. If you're not familiar with this behavior, this Digital Web article gives a good overview of the quirks.

The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each, or event-handler functions to use with bind. Functions created with the fat arrow are able to access properties of the this where they're defined.

http://coffeescript.org/

This is why this is binded to window.

You should use:

$('.menu a').click (event) ->
  event.preventDefault()
  console.log($(this).attr('href')) # it returns the link !

Upvotes: 2

Related Questions