Search code examples
javascriptmetaprogrammingjint

assigning a function to a name globally


I need a javascript function f that given another (anonymous) function g and a name n will assign g to that name in the global scope (or at least the current scope). I should be able to use it like this:

f(function(){ /* code */ }, "foo");

foo(); // this call should now work!

Is this possible? I need a pure JavaScript solution, no DOM-stuff or anything like that. This is not intended to run in any browser..

Disclaimer: I may or may not have a good/valid reason for wanting to do this. You do not need to lecture me on the virtue of keeping the global scope clean etc. ;)


Solution

  • As per Reid

    function f(g, n) {
        this[n] = g;
    }
    

    Or to be safer:

    function f(g, n) {
        (function() { return this; })()[n] = g;
    }