8

I suppose the following code:

jQuery("#mybutton").click(function(){

    //do something

});

How could I recall to this function "anonymous"?, I can not put a name to this function:

var xfun = function(){

    //do something

}

jQuery("#mybutton").click(xfun);

I can do something like this:

var working = false;
jQuery("#mybutton").click(function(){

  if (working){
    var _this = this;
    _this._eventType = e.type;
    setTimeout(function() { jQuery(_this).trigger(_this._eventType); }, 200);
    return false;
  }
  //do something

});

what I need is something like this:

var working = false;
jQuery("#mybutton").click(function(){

  if (working){
    setTimeout( this_function, 200);
    return false;
  }
  //do something

});

thanks.

EDIT:

Solution:

jQuery("#mybutton").click(function(){
  if (working){
    var fn = arguments.callee;
    var _this = this;
    setTimeout(function(){fn.call(_this);}, 200);
    return false;
  }
  //do something    
});
andres descalzo
  • 14,887
  • 13
  • 64
  • 115

2 Answers2

20

You can indeed name your anonymous function:

jQuery("#mybutton").click(function doWork(){
  if (working){
    setTimeout(doWork, 200);
    return false;
  }
  //do something    
});

You can also use arguments.callee:

jQuery("#mybutton").click(function(){
  if (working){
    setTimeout(arguments.callee, 200);
    return false;
  }
  //do something    
});

I'd go with the former.

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • 3
    @andres: np. Tis an important question considering the deprecation of `arguments.callee`: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/callee – Crescent Fresh Nov 24 '09 at 18:07
  • 3
    Only `Function.arguments.callee` is deprecated (the whole of `Function.arguments` is a terrible idea); `arguments.callee` is still OK. Whilst I too would probably go with the named function expression, note there is a bug in IE where the name is visible not only inside the function as expected, but also in the parent scope, as if you'd written a function statement. So make sure you don't use the name `doWork` in the surrounding function (or global). – bobince Nov 24 '09 at 18:39
  • with the modification that I show in question (edition), I could solve the problem that had the context of the function. thank @Crescent Fresh – andres descalzo Nov 25 '09 at 11:40
  • worth noting, a named function is no longer anonymous. it's just a closure. – buley Jul 04 '12 at 21:57
1

Can you explain why you can't name the function? You can use arguments.callee to get a reference to the current function, but that is deprecated and I'm not sure how much support it has among current browsers.

MMM
  • 7,221
  • 2
  • 24
  • 42
jthg
  • 2,790
  • 3
  • 29
  • 32