0

Let's say I do the following code:

class Test
  t: ->
    "hell"
  d: ->
    console.log t()
    "no"

It will compile to something like:

(function() {
  this.Test = (function() {
    function Test() {}
    Test.prototype.t = function() {
      return "hell";
    };
    Test.prototype.d = function() {
      console.log(t());
      return "no";
    };
    return Test;
  })();
}).call(this);

Ok, I can't call the method t() inside the d() method.

Why not? How can I fix it?

Thanks in advance.

1 Answer 1

10
class Test
  t: ->
    "hell"
  d: ->
    console.log @t()
    #           ^ Added
    "no"

In CoffeeScript, as in Javascript, methods on the prototype must be accessed as properties of this. CoffeeScript has shorthand for this, the @ character. @t() compiles to this.t(). And this.t() will execute Test.prototype.t() in the context on the instance you called it on.

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

2 Comments

gotcha. I need to tell to use this instance method, otherwise it will try to use a static method. Am I right? BTW: Thanks
@caarlos0 Not quite. @t() will execute an instance method, but t() won't access a static method on the class. t() looks for a local variable function shared in the current closure scope, and tries to execute it. This is neither a instance or static method, it's simply a local variable. And in this code, there is no local variable t anywhere.

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.