I read from the MDN docs that the first argument of .apply and .call is the “this” object, but
var stringToEval = "console.log(this)";
eval.call(null, stringToEval);
eval.apply(null, [stringToEval]);
in the code above both lines end up logging the Window object (in a browser). Shouldn’t it log null, that is what I passed as the first argument in both methods ?
From MDN:
The global object is window.
Edit since it doesn’t matter whether you pass in null, undefined, or an object with eval. Inside
eval,thiswill be the same asthisright before the eval call.As per section 15.1.2.1 of ECMA-262 5.1, eval takes in a string and parses it as ECMAscript. If it is valid ECMAscript then it runs it, in the context that it was called from. So in your case you can think of the calls to eval as if they replace themselves with
console.log(this)at runtime. With that replacement you end up with the program:Which makes it clear why it outputs the
DOMWindowobject twice. You can get around it like this:Since when eval replaces itself with
console.log(this)it will be in the context of that anonymous function in whichthiswill refer to the object passed in.See this JSFiddle