简体   繁体   English

使用console.log输出奇怪的输出(5)

[英]Strange output with console.log(5)

I have the simplest chrome extension which contains a content javascript (nothing else): 我有最简单的Chrome扩展程序,其中包含内容javascript(没有其他内容):

script="\
c=0;\
(function f() {\
    if (++c>20) return;\
    console.log(5);\
    setTimeout(f, 500);\
})();\
";
scriptBlock = document.createElement('script');
scriptBlock.type = 'text/javascript';
scriptBlock.appendChild(document.createTextNode(script));
document.getElementsByTagName('head')[0].appendChild(scriptBlock);

This simply injects a small piece of js into the head element. 这只是将一小块js注入头部元件中。 In mail.google.com, the console output is 4 fives followed by sixteen Resource interpreted as Other but transferred with MIME type undefined. 在mail.google.com中,控制台输出为4五,然后是十六个Resource interpreted as Other but transferred with MIME type undefined. Every other site displays simply 20 fives. 每个其他网站只显示20五。

Can anyone explain this behaviour please? 有人能解释一下这种行为吗?

You are using a global variable in your script. 您正在脚本中使用全局变量。 If a script in the page uses a global variable with the same name, it will change the value in the variable, and your script will show that value instead. 如果页面中的脚本使用具有相同名称的全局变量,则它将更改变量中的值,而脚本将显示该值。

As @Guffa said, your global variable may be overwritten. 正如@Guffa所说,你的全局变量可能会被覆盖。 Including it inside the closure will ensure it will be accessed by your code only. 将其包含在闭包内将确保仅由您的代码访问它。

(function () {
    var c = 0;

    setTimeout(function f() {
        if (++c > 20) return;

        console.log(5);

        setTimeout(f, 500);
    }, 500);
}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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