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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With