context = this
function test() {
(function(cmd) {
eval(cmd);
}).call(context, 'function foo(){}');
};
test();
foo(); // => ReferenceError: foo is not defined
how can I define a global function inside a function ? (using nodeJS)
A typical way to access the global object is calling a yielded value, e.g. from the comma operator.
function a() {
(0, function () {
this.foo = function () { console.log("works"); };
})();
}
a();
foo();
UPDATE:
Due to strict mode issues, here is another version (references: (1,eval)('this') vs eval('this') in JavaScript?, Cases where 'this' is the global Object in Javascript):
"use strict";
function a() {
(0, eval)('this').foo = function () { console.log("works"); };
}
a();
foo();
strict mode on ES5. Therefore i added an update, which should also work on strict mode.Use the global object in Node.JS:
function test() {
eval('function foo() { return "this is global"; }');
global.foo = foo;
};
test();
console.log(foo()); // this is global
function foo(), can't add "global"Foo defined in your other file? Is it global? Is it loaded alongside this script? Can you export the Foo function and require it in this script?function foo(){..}. I don't use require() because it need syntaxe module.export (this is incompatible with client side), so I read file and eval() itif (typeof exports != "undefined") module.exports = Foo. It's recommended not to use eval as it's slow and sometimes dangerous (also the contexts get wacky, as you've found out)foo is declared in the global context in your other file: after evaling it in your function, just go global.foo = foo;, as I have reflected in the answer
global... e.gglobal.yourFunctionName = function (arg1, arg2, ... , argN) { function body goes here };