Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fat arrow 'this' scope

Consider this code

 _bindEvents: ->
  @input.bind 'keyup', =>
    @filter($(this).val())
    if $this .val() is ''
      @clearBtn.hide()
    else
      @clearBtn.show()

it's clear to me that '@' represents '_this.' so it references the parent scope, but what if i need the 'inner this'.

Like this line:

@filter($(this).val())

compiles to this:

_this.filter($(_this).val()); // $(_this)

and I need this:

_this.filter($(this).val());  // $(this)

Is there a way to do that without using the thin arrow and saving the this reference by hand using a closue (that = this)?

like image 431
escusado Avatar asked May 20 '26 15:05

escusado


1 Answers

AFAIK there's no way to do that; and I would warn against it for a couple reasons:

  • ease-of-understanding: When you use a hash rocket (=>), you're effectively telling the reader that you need/want to preserve the current value of this; re-introducing a second this confuses that.

  • future-compatibility: From my understanding, the next ECMAScript spec is to support => in a way that it doesn't even introduce a new this. (And I wouldn't be surprised if CoffeeScript directly adopts the new arrow syntax when that feature lands)

A thin arrow w/ explicit referencing will probably make things more clear in the end.

like image 196
Nevir Avatar answered May 23 '26 17:05

Nevir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!