1

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?

Adam Halasz
  • 57,421
  • 66
  • 149
  • 213

1 Answers1

3

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.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • the reason why I would like to use `eval` is because the javascript is stored in a file, and I have to evaluate it. – Adam Halasz Apr 01 '13 at 22:24
  • and is there a way to get just the variables that were created inside the eval? With `this`, I'm getting all the objects from the global variable too in node.js – Adam Halasz Apr 01 '13 at 22:40
  • Please could you check out my further question which evolved from this one? http://stackoverflow.com/questions/15753308/javascript-how-to-get-the-variables-that-were-created-inside-a-function – Adam Halasz Apr 01 '13 at 23:07
  • @Adam: *"and is there a way to get just the variables that were created inside the eval? With this, I'm getting all the objects from the global variable too"* That suggests that in the context you're calling the code above, `this` refers to the global object. You can't get a list of `var` variables created within the `eval`, but if you can control the content of that file, you can have it define anything it wants to export as props on an object you give it. But you might consider reworking that external file into a proper module and including it via `require` rather than running it via `eval`. – T.J. Crowder Apr 02 '13 at 06:52