Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript instance variable

I'm learning CoffeeScript, and I've got one minor headache I haven't quite been able to figure out. If I create an object to do certain things, I occasionally need an instance variable for that object to be shared between methods. For instance, I'd like to do this:

testObject = 

  var message # <- Doesn't work in CoffeeScript.

  methodOne: ->
    message = "Foo!"

  methodTwo: ->
    alert message

However, you can't use var in CoffeeScript, and without that declaration message is only visible inside methodOne. So, how do you create an instance variable in an object in CoffeeScript?


Update: Fixed typo in my example so the methods are actually methods :)

like image 782
Andrew Avatar asked Apr 12 '12 21:04

Andrew


Video Answer


2 Answers

You can't like that. To quote the language reference:

Because you don't have direct access to the var keyword, it's impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that you're not reusing the name of an external variable accidentally, if you're writing a deeply nested function.

However what you're trying to do wouldn't be possible in JS either, it would be equivalent to

testObject = {
    var message;
    methodOne: message = "Foo!",
    methodTwo: alert(message)
}

which isn't valid JS, as you can't declare a variable in an object like that; you need to use functions to define methods. For example in CoffeeScript:

testObject =
    message: ''
    methodOne: ->
        this.message = "Foo!"
    methodTwo: ->
        alert message

You can also use @ as a shortcut for 'this.', i.e. @message instead of this.message.

Alternatively consider using CoffeeScript's class syntax:

class testObject
    constructor: ->
        @message = ''

    methodOne: ->
        @message = "Foo!"

    methodTwo: ->
        alert @message
like image 198
Lauren Avatar answered Oct 05 '22 23:10

Lauren


Just to add to @Lauren's answer, what you wanted is basically the module pattern:

testObject = do ->

  message = null

  methodOne = ->
    message = "Foo!"

  methodTwo = ->
    alert message

  return {
    methodOne
    methodTwo
  }

Where message is a "private" variable only available to those methods.

Depending on the context you could also declare message before the object so that it's available to both methods (if executed in this context):

message = null

testObject = 
  methodOne: -> message = "Foo!"
  methodTwo: -> alert message
like image 29
Ricardo Tomasi Avatar answered Oct 06 '22 00:10

Ricardo Tomasi