CoffeeScript和OOP -原型方法

CoffeeScript and OOP - prototype methods

本文关键字:原型 方法 OOP CoffeeScript      更新时间:2023-09-26

假设我执行以下代码:

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

它将编译成如下内容:

(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);

好的,我不能在d()方法中调用t()方法。

为什么不呢?我该怎么修理它?

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

在CoffeeScript中,和Javascript一样,原型上的方法必须作为this的属性来访问。CoffeeScript有this的简写,即@字符。@t()编译为this.t()。并且this.t()将在您调用它的实例的上下文中执行Test.prototype.t()