JavaScript - Passing a reference to this current anonymous function

前端 未结 4 1043
忘掉有多难
忘掉有多难 2021-02-05 08:19
window.addEventListener(\'unload\', function(e)
{
    MyClass.shutdown();
    window.removeEventListener(\'unload\', /* how to refer to this function? */);
}, false);
         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 09:22

    Name your function.

    function f(e) {
       MyClass.shutdown();
       window.removeEventListener('unload', f);
    }
    window.addEventListener('unload', f, false);
    

    Edit I think this will work too. Good point Kobi!

    window.addEventListener('unload', function f(e)
    {
        MyClass.shutdown();
        window.removeEventListener('unload', f);
    }, false);
    

提交回复
热议问题