How to Make a Generic Javascript Method Closure

The Problem

I recently found myself writing a custom Javascript API to integrate a Flash widget written by an external vendor. I was making the API object oriented, so it could be instantiated and controlled simply like:

var myWidget = new FlashWidget()
myWidget.doStuff()

Things were going well, until I realized I had overlooked a minor detail in the Flash widget. For several actions, the widget accepts functions names, which it will later evaluate and call when the actions complete. The detail I missed was that it only accepts function names visible in the global scope. Since all my methods are bound to myWidget, and not the global scope, the Flash widget won’t be able to directly call anything in my nice API. I had hoped it would be smart enough to accept a qualified name, like “myWidget.doStuffCallback”, and resolve it correctly but no such luck.

I Need Closure

Fortunately, I’m well acquainted with the concept of Javascript closures, so the solution turned out to be a few extra lines of code to expose my callbacks in a way that the Flash widget would accept. Essentially, I needed to create an anonymous function which would call the given method, remaining bound to the myWidget scope, and include any additional arguments the widget might pass over.

Some Javascript frameworks, like the well-known Prototype framework, have various helper functions to accomplish something like this, but they usually boil down to this simple bit of code:

function methodClosure(obj, funcName){
    return function(){
        return obj[funcName].apply(obj, arguments)
    }
}

With this, I can easily expose my callbacks simply like:

doStuffCallback = methodClosure(myWidget, 'onDoStuff')

Leave a Reply