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)
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();
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