1
0

More than 3 years have passed since last update.

【Javascript】即時関数でグローバルオブジェクトを定義する。

Last updated at Posted at 2020-06-16

メモとして残します。

レガシーではありますが、トランスパイル抜きにした場合で、IEにも対応するグローバルオブジェクトの定義をメモ。

■やり方

(function (global) {
    var HogeObject = (function () {
      function HogeObject() {
        //コンストラクタ
      }

      HogeObject.prototype.setHoge = function (value){
        this.hoge = value
      }
      HogeObject.prototype.getHoge = function (){
        return this.hoge
      }


      return HogeObject;
    })();

    global.HogeObject = HogeObject;
  }(this));

上記のコード読み込み後は任意の場所で下記のように呼び出せばOK。

const  hogeobj = new HogeObject() 'IE10の場合はconstをvarに

■さいごに

今時であれば、トランスパイルしていい感じにコードをビルドしてデプロイする方がいいと思いますが、
たまたまレガシーな案件があったため、せっかくなので、投稿しました。
IEガン無視していいのであれば、他の言語同様にclassで定義できるののに。。。

1
0
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
1
0