[英]Why do JSfiddle and Chrome console return different values of the same function?
I have the following code in JSfiddle
. 我在
JSfiddle
有以下代码。
var a = 1;
function five() {
this.a = 5;
console.log(a); //JSfiddle prints the value 1
}
five()
But when I paste the same exact code inside Chrome console, the function five()
prints 5. Why? 但是当我在Chrome控制台中粘贴相同的代码时,函数
five()
打印5.为什么?
By default JSFiddle wraps your code in the window.onload
event, so you're actually running this: 默认情况下,JSFiddle将您的代码包装在
window.onload
事件中,因此您实际上正在运行此代码:
window.onload = function() {
var a = 1;
function five() {
this.a = 5;
console.log(a); //JSfiddle prints the value 1
}
five()
}
That means that a
is local to that function, while this
still refers to the global object ( window
). 这意味着
a
是该函数的本地,而this
仍然是指全局对象( window
)。 In the Chrome console, without the wrapper function, var a
is creating a global variable, which are created and stored as properties on the global object , and is thus the same as window.a
/ this.a
. 在Chrome控制台中,没有包装函数,
var a
正在创建一个全局变量,它在全局对象上创建并存储为属性 ,因此与window.a
/ this.a
相同。
If you go to the JavaScript options and choose either of the "nowrap" options, it will log 5
in JSFiddle too: 如果你转到JavaScript选项并选择“nowrap”选项之一,它也将在JSFiddle中记录
5
:
I would write the code this way to make it work 'everywhere' 我会用这种方式编写代码,使其“无处不在”
var obj = {};
obj.a = 1;
obj.foo = function five() {
this.a = 5;
window.alert(this.a);
}
obj.foo();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.