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, eg 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.