简体   繁体   English

为什么JSfiddle和Chrome控制台会返回相同功能的不同值?

[英]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.

相关问题 为什么对同一函数的两个绑定返回不同的值 - Why two bindings to the same function return different values 为什么我的函数返回与Chrome浏览器中的console.log()不同 - Why is my function return different than my console.log() in Chrome browser 为什么在使用工厂 function 与构造函数 function 时,Chrome 控制台中的对象看起来不同? - Why do objects in the Chrome console appear different when using a factory function vs a constructor function? 为什么相同的代码在jsfiddle中给出不同的结果 - Why the same code give different result in jsfiddle 为什么在节点env和chrome控制台之间运行相同的代码会有所不同? - Why running same code is different between node env and chrome console? 在读取相同文件的Chrome和FireFox中,FileReader对象返回不同的值 - FileReader objects return different values in Chrome and FireFox reading the same file 为什么Node crypto为同一个字符串返回不同的值? - Why does Node crypto return different values for the same string? 将 Python 函数返回到 Chrome 控制台 - Return Python function onto Chrome console 为什么此javascript函数针对同一查询返回两个不同的结果? - Why does this javascript function return two different results for the same query? 为什么chrome的开发者控制台“复制到剪贴板”功能有时会返回对象的toString值? - Why does chrome's developer console copy-to-clipboard function return the object's toString value sometimes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM