I’m trying to access an instance method inside of a map call, unfortunately my reference to the instance object is being redefined to Window. I’m not sure how to get a hold of my instance method:
class Test
constructor: (@an_array) ->
f: () ->
@an_array.map (value) ->
@a(value)
a: (value) ->
alert value
t = new Test [1, 2, 3]
t.f() // TypeError: Object [object Window] has no method 'a'
There are various ways to deal with this.
The most common in CoffeeScript would be to use a fat arrow (
=>) to produce a bound function:Demo: http://jsfiddle.net/ambiguous/6BW8q/
The standard JavaScript approaches will also work (and sometimes would be necessary or more appropriate):
Save a reference to
@so that you don’t have to care whatthisis inside the callback function:Demo: http://jsfiddle.net/ambiguous/XhP4z/
I tend to use
_thisinstead ofselfas the name for this thing due to the existence ofwindow.selfand the interesting bugs that causes if you forget thevarin JavaScript.Manually create a bound function using
Function.bind, this isn’t quite universally supported though:Demo: http://jsfiddle.net/ambiguous/n2XnC/
Use jQuery’s
$.proxy, Underscore’s_.bind, or some other non-native bound function implementation:Demo: http://jsfiddle.net/ambiguous/LAy9L/
Which one you choose depends on your environment and specific needs:
=>so you’ll need to use some variant of (2) or (3) above (or possiblyFunction.callorFunction.apply).thisat the same time then you’d go with (1).bindexists then you’ probably end up with (3) and which branch of (3) would probably depend on which library you already have available.