To add to the answers already present based on the comments on Kira's answer, you seem to have a fundamental misunderstanding of how scoping works. Javascript has lexical scoping, meaning scope is defined by the structure of the source code, with one exception: this
. this
is dynamically scoped, meaning that scope is defined by the caller. In code:
bar = 3
test = (foo) ->
foo + bar # bar can be seen, because its in an outer scope test can see
So far so good. Now lets define a class:
class Test
constructor: (@foo) ->
getFoo: -> @foo
The getFoo
part is equivalent to Test.prototype.getFoo = function...
. The this
(@) is scoped to getFoo
. The invoker of getFoo
determines the this
:
obj1 = new Test 2
obj1.getFoo() # 2
fn = Test.prototype.getFoo;
fn()
fn
is now a stand alone function instead of a method of obj1
. When we call fn
one of two things will happen. If we're in strict mode it will throw an error. Because we're invoking in a global context this
in getFoo
is undefined. In non-strict it will be the global window
and it will look for a foo property that probably isn't there.
We can force the this
value via bind
, call
, or apply
.
obj2 =
foo: 3
Test.prototype.getFoo.call(obj) # 3
Here we've used it to 'borrow' a method of the Test class. So where does bind come in? Lets say that our class has a method we know will be used in a different context, like an event handler:
class Test
constructor: (@foo) ->
@clickHandler = Test.prototype.clickHandler.bind this
clickHandler: (e) ->
console.log @foo
Because we'll be passing the method to .addEventListener
the this
context will evaporate, meaning we'll need to bind it to each instance, which we do in the constructor.