最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CoffeeScript and OOP - prototype methods - Stack Overflow

programmeradmin4浏览0评论

Let's say I do the following code:

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

It will pile 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.

Let's say I do the following code:

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

It will pile 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.

Share Improve this question asked Jan 15, 2013 at 20:45 caarlos0caarlos0 20.7k27 gold badges89 silver badges160 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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() piles to this.t(). And this.t() will execute Test.prototype.t() in the context on the instance you called it on.

发布评论

评论列表(0)

  1. 暂无评论