Matrix Matrix - 2 months ago 12
Javascript Question

How define function in javascript in global context inside a function?

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)

Answer

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

Comments