LoginSignup
27
26

More than 5 years have passed since last update.

CoffeeScriptで定義したクラスを外部から呼び出す

Last updated at Posted at 2013-07-18
class Hoge
  constructor: () ->
    console.log "hello"

のように宣言したものをviewなどのJavaScriptから

new Hoge();

などと呼びだそうとするとそんなもんねーよと言われてしまいます。

それもそのはず、冒頭のCoffeeScriptはファイルとして

(function() {
  Hoge = (function() {
    function Hoge() {
      console.log("hello");
    }
    return Hoge;
  }();
}).call(this);

のように (function() {...}).call(this);で括られててしまうから外からアクセスできません。
外から呼び出すにはclass名の前に@を入れて

class @Hoge
  constructor: () ->
    console.log "hello"

と書けば

(function() {
  this.Hoge = (function() {
    function Hoge() {
      console.log("hello");
    }
    return Hoge;
  })();
}).call(this);

になるのでview側などから

new Hoge();

できるようになります。

27
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
26