Tuesday, 10 September 2013

How to use set methods to initialize instance variables via constructor in coffeescript

How to use set methods to initialize instance variables via constructor in
coffeescript

I have a "class" in coffee script whose instance variables I want to
initialize with instance methods that return a value via a callback, but
it doesn't work as I had hoped:
class MyClass
constructor: ->
@datamember: setDatamember()
setDatamember: ->
someFunction (response) ->
@datamember = response
getDatamember: ->
return @datamember
----
myObj = new MyClass
console.log myObj.getDatamember
The result I get suggests that "this" in setDatamember is referring to
something different from what "this" refers to in the object instance. If
I explicitly call myObj.setDatamember, I get the expected result, but is
there any way to call on a set method -- specifically one that sets the
data member via a callback -- in the constructor? I've looked through the
docs, as well as various other sources of coffeescript info (e.g. this
one), and I haven't found anything that touches upon this.

No comments:

Post a Comment