Stefan Ramson
Stefan Ramson

Reputation: 541

Use variables in scope of a given function without passing

I want to use local variables like 'thisModule' in scope of the given 'functionToRun' without passing them as parameters.

Onsetsu.run = function (functionToRun) {
    var thisModule = Onsetsu.namespace(resolvedModule.moduleName);
    functionToRun();
};

Onsetsu.run(function() {
    /* thisModule should be visible here */
});

Unfortunately 'thisModule' is not defined in the scope. Is there a convinient way to bring 'thisModule' into the functions scope?

Upvotes: 0

Views: 93

Answers (2)

gilly3
gilly3

Reputation: 91497

Define a variable in the closest shared scope of functionToRun and Onsetsu.run. Assign the variable within Onsetsu.run:

var thisModule;
Onsetsu.run = function (functionToRun) {
    thisModule = Onsetsu.namespace(resolvedModule.moduleName);
    functionToRun();
};

Onsetsu.run(function() {
    /* thisModule should be visible here */
});

Assuming your actual code is more complicated than that:

(function(){
    var thisModule;
    var Onsetsu = (function(){
        var resolvedModule = { moduleName: "something" };
        return {
            run: function (functionToRun) {
                thisModule = Onsetsu.namespace(resolvedModule.moduleName);
                functionToRun();
            },
            namespace: function(moduleName){ ... }
        };
    })();
    Onsetsu.run(function() {
        /* thisModule should be visible here */
    });
})();

If Onsetsu is a library that you can't (or don't want to) modify, then you are out of luck.

Edit: You could also assign a property on the function itself:

Onsetsu.run = function (functionToRun) {
    var thisModule = Onsetsu.namespace(resolvedModule.moduleName);
    functionToRun.module = thisModule;
    functionToRun();
};

You can access the property from within functionToRun via arguments.callee:

Onsetsu.run(function() {
    var module = arguments.callee.module;
});

Or by giving the function a name:

Onsetsu.run(function fn() {
    var module = fn.module;
});

Upvotes: 1

Ibu
Ibu

Reputation: 43810

You can attach thisModule to the this reference inside functionToRun

Onsetsu.run = function (functionToRun) {
    var thisModule = Onsetsu.namespace(resolvedModule.moduleName);
    functionToRun.apply(thisModule,[]);
};

So inside your function you can refer to thisModule like so:

function myFunc(){
    console.log(this); // which will refer to thisModule
}
Onsetsu.run(myFunc);

Upvotes: 1

Related Questions