2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CoffeeScript 名前空間

Last updated at Posted at 2016-02-02

Rails とかで JavaScript をメインに使っていて、CoffeScript を混ぜ始めると、JavaScript と同様にグローバルで関数などを作ろうとして、ハマりました。

CoffeeScript で

method1 = (args) ->
  # do something

と書くと、自動的に

(function() {
  var method1;

  method1 = function (args) {
    # do something
  };
})();

となり、グローバルではなく、ローカルで処理しようとするので、他のところで使えなくなってしまいます。

代わりに

window.YourNamespace or= {}  # 既にある場合に再定義しないように
ns = window.YourNamespace

ns.method1 = (args) ->
  # do something

と名前空間に入れてあげると他のところ(他の JavaScript ファイルなど)でも使えるようになります。

参考リンク

Namespacing in coffeescript - Stack Overflow

2
2
2

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?