문제

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/

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top