LoginSignup
2
1

More than 3 years have passed since last update.

ES6{}でブロックスコープを作ったら中身が グローバル変数になった話

Last updated at Posted at 2019-07-08

はじめに

弊社はES6で記載したコードをbabelでES5にトランスパイルしてます。
いつか問題が起きそうだなって思ってたら本当に起きたので備忘録として残しておきます。

前提

今回問題が起きたページでは複数のjsファイルが読み込まれていて、トータルするとかなりのjsコードが書かれています。

やりたかったこと

モーダルを表示後、「ばつボタン」もしくは「モーダル外」をクリックするとモーダルが閉じる。

問題が起きたコード

common.js
{
    const
         target = document.getElementById('commonPopup')
        ,targetCloseTrigger = document.getElementsByClassName('_close')[0]
    ;   

    const popupAni = {
        popupDisplay : ()=> {
            target.classList.remove('_no_show');
            target.classList.add('_is_show');
        },

        popupClose : ()=> {
            target.style.transition = ".7s";
            target.classList.remove('_is_show');
            target.classList.add('_no_show');
        }
    }

    window.addEventListener('load', ()=> {
        setTimeout(popupAni.popupDisplay(),5000);
    });
    targetCloseTrigger.addEventListener('click',()=> {
        popupAni.popupClose();
    });
}

上記はモーダルの表示と閉じる時に使われる関数です。
エラー内容をコピるの忘れてました。すみません。
ざっくりとtargetの中のtransitionはundefinedだよって感じです。

起きた問題

結論、モーダルのtarget変数が、後読みされる別のtarget変数に上書きされていました。

ES6をトランスパイルした際、{}はグローバルスコープとして認識されない

ES5にはconstletという概念は存在せず、トランスパイルでvarに変換され、
{}で括られた変数たちはグローバル変数になりました。

解決策

{}ではなく即時関数で括る

common.js
(function(){
    const
         target = document.getElementById('commonPopup')
        ,targetCloseTrigger = document.getElementsByClassName('_close')[0]
    ;   

    const popupAni = {
        popupDisplay : ()=> {
            target.classList.remove('_no_show');
            target.classList.add('_is_show');
        },

        popupClose : ()=> {
            target.style.transition = ".7s";
            target.classList.remove('_is_show');
            target.classList.add('_no_show');
        }
    }

    window.addEventListener('load', ()=> {
        setTimeout(popupAni.popupDisplay(),5000);
    });
    targetCloseTrigger.addEventListener('click',()=> {
        popupAni.popupClose();
    });
})();

いったんはこれで解決しました。
そもそも変数名が単調すぎるって問題もありますが。。。

参考サイト

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