blakev
blakev

Reputation: 4449

Cross module function scope? Where is it looking

Given the following:

include.js

module.exports = function() {

    ...

    return {
        func: function(val) {
            return Function('return ' + val + ';');
        }
    }
}()

running.js

var outer = function() {
    var include = require('./include.js');

    var x = include.func('eq');

    console.log(x(5, 5));
}
outer()

...where would I put function eq(x, y){ return x === y; } such that this would work? I'm currently getting an eval at <anonymous> on the line that calls the function; x(5,5) in this case.

It doesn't like when eq is in include.js or when it's in running.js ~ I know this is example code is taken from my project and made pretty ambiguous...but, if it's possible, where would that function go?

OR

...would it be better to define an object of functions where the keys are the name of the function?

defaultFuncs = {
    'eq': function(x, y){ return x === y; }
}

Upvotes: 0

Views: 81

Answers (1)

Bergi
Bergi

Reputation: 664185

The parent scope of functions created via new Function is the global scope, not any local or module scope. So

global.eq = function(a,b) { return a==b };
function func(name) { return Function("return "+name+";"); }

var x = func("eq");
var equals = x();
equals(5, 5) // true

should work.

...would it be better to define an object of functions where the keys are the name of the function?

Definitely yes.

Upvotes: 2

Related Questions