Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the same code give different result in jsfiddle

Tags:

javascript

window.scope = 'global'
Object.prototype.scope = 'object proto'

console.log(scope);

I'm writing above simple script to test the scope, but I got different result in chrome dev tools and jsfiddle.

  • chrome: 'object proto';
  • jsfiddle: 'global';

Why?

like image 432
Rick Li Avatar asked Nov 10 '22 16:11

Rick Li


1 Answers

If I paste your code into a new HTML document and view in Chrome, I get global printed to the console when the page is loaded.

When you paste your code into the DevTools console directly, you get:

object proto
undefined

And that is because what the DevTools actually evaluates is the following script (in my case):

with ((console && console._commandLineAPI) || {}) {
  window.scope = 'global'
  Object.prototype.scope = 'object proto'

  console.log(scope);
}

So, by using the with statement, the console is added to the current scope chain which binds the scope variable to it. Since you're extending the object prototype before accessing the scope, you see the result of your operation when referencing scope (which actually refers to console.scope, thanks to with statement).

The reason why there' two lines of output is obvious: first, the console.log gets executed and so the message is printed onto the console, then the DevTools gives you the result of the expression console.log which is nothing (the function doesn't have a return value).

Hope this clarifies things a bit for you.

like image 107
volpav Avatar answered Nov 14 '22 23:11

volpav