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 :)
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