Search code examples
javascriptcoffeescriptprivate-methodspublic-method

Getting "public variable" in a "private method" using CoffeeScript


I have the following code:

class Example

  @text = 'Hello world! ;)'

  getText = ->
    @text

  constructor: ->
    alert(getText())

### Instance ###
example = new Example

This will return 'undefined', Is there any way to make it return the @text content?

http://jsfiddle.net/vgS3y/


Solution

  • This is a common error in CoffeeScript. Look at the compiled JavaScript:

    Example = (function() {
      var getText;
    
      Example.text = 'Hello world! ;)';
    
      getText = function() {
        return this.text;
      };
    
      function Example() {
        alert(getText());
      }
    
      return Example;
    
    })();
    

    Using @ in the class definition creates a static method or variable. That is, it's attached to the class object.

    If you're trying to make it an instance variable, set it in your constructor.

    constructor: ->
      @text = 'Hello world! ;)'
      alert(getText())
    

    If you're trying to access the static property, refer to the class name.

    getText = ->
      Example.text