Javascript: Return values created in eval

I would like to do something like this:

function end(){ console.log(this); } // <-- the problem is here with `this`
eval('var a = 0; setTimeout(function(){ a = 10; end(); }, 2000)');

which 2 seconds later should output:

{ "a" : 10 }

Is this somehow possible?

Yes:

function end(){ console.log(this); }
eval('var a = 0, self = this; setTimeout(function(){ a = 10; end.call(self); }, 2000)');

Note that I set a variable, self, to be this, and then use Function#call when calling end, which allows us to set a specific value for this during the call. This works because the anonymous function passed to setTimeout has a reference to the execution context in which it was created and all variables within that, and so has access to self (and a).

If there's not a really good reason for using eval (and I don't see one here), I wouldn't, just do this:

function end(){ console.log(this); }
var a = 0, self = this; setTimeout(function(){ a = 10; end.call(self); }, 2000);

You can also create a second function that, when called, turns around and calls end with the right this value. This is called binding, and is facilitated by the ES5 Function#bind function:

function end(){ console.log(this); }
var a = 0, boundEnd = end.bind(this); setTimeout(function(){ a = 10; boundEnd(); }, 2000);

Since you're using NodeJS, you're using V8, which has Function#bind. (If you were doing this in a browser, you'd have to be careful to provide a shim for bind if you needed to support older browsers.)