简体   繁体   English

JavaScript - 传递对此当前匿名函数的引用

[英]JavaScript - Passing a reference to this current anonymous function

window.addEventListener('unload', function(e)
{
    MyClass.shutdown();
    window.removeEventListener('unload', /* how to refer to this function? */);
}, false);

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);

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. 在Javascript中,arguments.callee属性包含一个指向当前正在执行的函数的指针,这意味着匿名函数确实可以调用自身。

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

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

The callee property of the arguments object always refers to the called function: arguments对象的callee属性总是引用被调用的函数:

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

See: MDC: callee 请参阅: MDC:被调用者

I haven't tried this, but how about moving the removeEventListener method call into MyClass itself. 我没有尝试过这个,但是如何将removeEventListener方法调用移动到MyClass本身。 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. 我想这取决于MyClass的作用以及你如何使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM