2

Say I have a Coffeescript class like this:

class Foo
    aVar = 'foo'

    someFunction = ->
        anotherVar = 'bar'

Is there a way to set anotherVar as a class variable without having to declare it as null, like so:

class Foo
    aVar = 'foo'
    anotherVar = null

    someFunction = ->
        anotherVar = 'bar'

2 Answers 2

2

No, you can't. Let us look at a simple class:

class C
    cv = null
    m: -> cv

That is converted to this JavaScript:

var C = (function() {
  var cv;
  function C() {}
  cv = null;
  C.prototype.m = function() {
    return cv;
  };
  return C;
})();

You'll notice that the "private class variable" cv is just a local variable inside the self-executing function that builds C. So, if we wanted to add a new "private class variable" to C, we'd have to open that anonymous function's scope again and add new variables. But there's no way to travel back in time and alter the scope of a function that has already executed so you're out of luck.

You don't have to define your anotherVar as null when you define it but you have to initialize it to something.

Sign up to request clarification or add additional context in comments.

1 Comment

Lame, I thought there may be a way, like you can do with static vars by prepending @; oh well!
0

Have you ever heard about this keyword? :) CoffeeScript maps @ into this:

class Foo
    aVar = 'foo'

    someFunction: ->
        @anotherVar = 'bar'

5 Comments

But that makes it a 'public' (static) variable, I want it to be 'private', e.g. for it to only exist and be accessible within the class.
There is no such thing as private variables in JavaScript. That's one thing. And the second: someFunction is mapped to a property of prototype of Foo. The code you've wrote above won't even work. Prototype functions can only access variables within this context. If you want to use private variables, then you have to define someFunction within a constructor of Foo with @ prefix.
Woops! I've updated my question to reflect the rewriting of someFunction.
But you can simulate private in certain contexts by taking advantage of the function wrappers: stackoverflow.com/a/9347993/479863
@muistooshort Oh, yeah. I forgot that CoffeeScript wraps everything again in an anonymous function. Thank you for remainding me!

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.