5
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.

名前空間の汚染を防ぐためのモジュール化

Posted at

中規模のアプリケーションをJavaScriptでプログラミングすると思わぬところで変数名や関数名の重複が発生してトラブルになります。

グローバルスコープの汚染を防ぐには色々方法があり、変数のスコープ等、色々と理解すべきことは多いのですが、即時関数の中にメソッドを定義することで解決する方法をメモしておきます。

var NameSpace = NameSpace || {}; //グローバル変数を生成

//即時関数を作成してその中に関数をまとめる
(function(_) {
    var name = "Qiita";
    function getName() {
        return name;
    }
    _.displayName = function() {
        console.log(getName());
    };
    _.setName = function(x) {
        name = x;
    };
})(NameSpace); //即時関数に名前空間用のグローバル変数を渡す

//利用側
NameSpace.displayName(); // Qiitaと表示
NameSpace.setName("New Qiita");
NameSpace.displayName(); // New Qiitaと表示
5
2
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
5
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?