Tiddo
Tiddo

Reputation: 6544

JavaScript reference to anonymous function from inside that function

I'm creating a small canvas library in which I have an anonymous function which needs to reference to itself. However, I don't know how to do this. I have the following incomplete code:

var removeDragHandler = (function (object) {
  return function (e) {
    if (typeof object["dragend"] === "function") {
      object["dragend"](e);
    }
    removeEvent({
      element: window,
      event: "mousemove",
      callback: object["drag"]
    });
    removeEvent({
      element: window,
      event: "mouseup",
      callback: ????? //What here?
    });
  };
})(object);
addEvent({
  element: window,
  event: "mouseup",
  callback: removeDragHandler
});

Of course I could replace the ????? with arguments.callee, but then it doesn't work in strict mode. Are there any other options?

Upvotes: 2

Views: 144

Answers (1)

Esailija
Esailija

Reputation: 140210

You can give a name to the anonymous function. Note that there is a bug in older IE where the anonymous function leaks as a declared function in the outer scope but that should not be issue here since that outer scope is pretty empty anyway.

var removeDragHandler = (function (object) {
  return function once(e) {
    if (typeof object["dragend"] === "function") {
      object["dragend"](e);
    }
    removeEvent({
      element: window,
      event: "mousemove",
      callback: object["drag"]
    });
    removeEvent({
      element: window,
      event: "mouseup",
      callback: once
    });
  };
})(object);

Upvotes: 2

Related Questions