JavaScript - Passing a reference to this current anonymous function

前端 未结 4 1040
忘掉有多难
忘掉有多难 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:13

    I haven't tried this, but how about moving the removeEventListener method call into MyClass itself. The method won't be anonymous, but you won't be polluting the global namespace and it will be part of the class it's manipulating. You can even make it "private". I'm not sure what your style is, but I'd write it something like this:

    var MyClass = function(){
      var self = this;
      self.shutdown = function(){ 
        window.removeEventListener('unload',self.shutdown,false);
      };
      self.initialize = function() {
        window.addEventListener('unload',self.shutdown,false);
      };
      return self;
    };
    var myObject = new MyClass();
    myObject.initialize();
    

    I guess it depends on what MyClass does and how you use it.

    0 讨论(0)
  • 2021-02-05 09:16

    The callee property of the arguments object always refers to the called function:

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

    See: MDC: callee

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-05 09:25

    Howto use recursion on Anonymous Functions

    Lets say we have an anonymous factorial function and we want to do it recursively. How do we call a function without a name? Well in Javascript the arguments.callee property contains a pointer to the currently executing function which means an anonymous function can, indeed, call itself.

    alert((function(n){ if(n <= 1){return 1;}else{return n*arguments.callee(n-1);}})(10));
    

    source: http://www.hunlock.com/blogs/Functional_Javascript

    0 讨论(0)
提交回复
热议问题