Reputation: 43153
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 :)
Upvotes: 11
Views: 11313
Reputation: 35283
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
Upvotes: 5
Reputation: 123563
You can define the property with:
message: null
But, you aren't currently defining methods -- you need ->
for that.
Then, to refer to instance properties within the methods, prefix the property names with @
.
testObject =
message: null
methodOne: ->
@message = "Foo!"
methodTwo: ->
alert @message
Upvotes: 1
Reputation: 1500
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
Upvotes: 12
Reputation: 10646
Use @
to point to this
testObject =
methodOne: ->
@message = "Foo!"
methodTwo: ->
alert @message
fixed version on coffeescript.org
Upvotes: 0