tooba
tooba

Reputation: 569

Coffeescript class losing functions

I have a CoffeeScript which I can't call functions from. But if I declare an instance of it and add functions to the instance it works. What am I missing?

Function doesn't get called:

  class testClass 
    username: 'Fred'

    this.testFunction = ()->
      alert 'test'

  test = new testClass

  test.testFunction()   

Function works:

  class testClass 
    username: 'Fred'

  test = new testClass

  test.testFunction = ()->
    alert 'test'

  test.testFunction()

Upvotes: 0

Views: 216

Answers (2)

Trevor Burnham
Trevor Burnham

Reputation: 77416

Within the class body, this points to the class itself, not its prototype. What you want is

class testClass 
  username: 'Fred'

  testFunction: ->
    alert 'test'

Writing this.testFunction =, on the other hand, creates testClass.testFunction.

Upvotes: 4

driis
driis

Reputation: 164281

Try

 class testClass 
    username: 'Fred'
    testFunction: ()->
      alert 'test'

  test = new testClass

  test.testFunction()   

Coffeescript has classes as a first level concept; the this.testfunction = is wrong. You should just define it as a field of type function.

Upvotes: 1

Related Questions