[英]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 dev工具和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. 如果我将您的代码粘贴到新的HTML文档中并在Chrome中查看,则在加载页面时我会将global
打印到控制台。
When you paste your code into the DevTools console directly , you get: 将代码直接粘贴到DevTools控制台时,您会得到:
object proto
undefined
And that is because what the DevTools actually evaluates is the following script (in my case): 这是因为DevTools实际评估的是以下脚本(在我的例子中):
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. 因此,通过使用with
语句, console
将添加到当前作用域链中,该scope
将scope
变量绑定到它。 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). 由于您在访问scope
之前扩展了对象原型,因此在引用scope
时会看到操作的结果(实际上是指console.scope
,感谢with
语句)。
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). 有两行输出的原因很明显:首先, console.log
被执行,所以消息被打印到控制台上,然后DevTools给你表达console.log
的结果,这是什么都没有 (函数没有没有回报值。
Hope this clarifies things a bit for you. 希望这能为您澄清一些事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.