简体   繁体   中英

Why the same code give different result in jsfiddle

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM