Matrix
Matrix

Reputation: 3369

How force use "this" in coffeeScript?

I need to define one static method in MotherClass like that:

class @MotherClass
  @test = =>
    Foo.bar(this) # same with @

but if u try it: http://coffeescript.org/#usage, you will see, this is automaticly compile in "MotherClass".

So, it's the same, but not realy!

In fact, I have a ChildClass in inheritance with MotherClass

  @ChildClass extends @MotherClass

So ChildClass.test() is defined. But like that:

function() {
    return Foo.bar(MotherClass);
};

I need first param of Foo.bar is ChildClass in ChildClass (and ChildClass2 if I make ChildClass2 class...), not MotherClass. So I need dynamic this, not static.

How force write "this" in CoffeeScript?

thx.

EDIT: I found "burk !" solution ^^ => "eval('this')", but it's realy crapy way. How do better?

Upvotes: 1

Views: 52

Answers (1)

Blender
Blender

Reputation: 298166

Use the skinny arrow instead of the fat arrow:

class @MotherClass
  @test = ->
    Foo.bar(this)

The fat arrow makes your function bound to MotherClass.

Upvotes: 1

Related Questions