0

I have a file 'a.coffee', with the following code:

class Options
  options:
    # ...

  setOption: (name, value) ->
    # ...

  getOption: (name) ->
    # ...

# Export the Options class.
module.exports = Options

And file 'b.coffee':

Options = require './a'
console.log new Options()

Of course, it is expected that when I run b.coffee, I will see this output:

{
  options: ...,
  setOption: function (name, value),
  getOption: function (name)
}

But instead, I get {}.

How can I fix this?

1 Answer 1

3

Your expectations are wrong. Everything at the class level goes in the object's prototype so given this:

class C
  p: 6
  m: ->
o = new C

the object o will be empty because there are no instance variables but if you look at the "class" (via Object.prototype.constructor to get the "class" and :: to get the prototype):

o.constructor::p

you'll see things.

If you add some instance variables (i.e. something that really is part of your object):

class C
  constructor: -> @p = 6

then you'll see them in the object:

c = new C
console.log c
# { p: 6 } will appear in the console
Sign up to request clarification or add additional context in comments.

5 Comments

But this seems to go against what is demonstrated at coffeescript.org/#classes
How so? I don't see any discrepancies. You can o = new Options; o.getOption('x') just fine due to prototypical inheritance.
Then it seems the problem I am having is different from what I thought - I had a more detailed class here: raw.githubusercontent.com/htmlguy/elapse/master/src/… and nodejs was reporting an error when the getOption function is called. I suppose I'll have to make a new question for my real problem.
I don't see anything obviously wrong with your getOption. BTW, "wether" is a ram or goat with a certain anatomical modification, the word you're looking for is "whether".
Thank you. I fixed the actual problem on my own, still not sure exactly what it was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.