为什么返回后的变量提升在某些浏览器上起作用,而在某些浏览器上不起作用? [英] Why variable hoisting after return works on some browsers, and some not?

查看:72
本文介绍了为什么返回后的变量提升在某些浏览器上起作用,而在某些浏览器上不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

alert(myVar1);
return false;
var myVar1;

以上代码在IE,FF和Opera中引发错误,表明该函数必须包含return语句.但是它在Safari和Chrome中有效(显示undefined).

Above code throws error in IE, FF and Opera stating that return statement has to come in the function. But it works (shows undefined) in Safari and Chrome.

以上代码已在全局范围内编写.在所有功能之外.

The above code has been written in global scope. Outside all the functions.

有什么理由吗?

推荐答案

在javaScript中,将变量移到脚本顶部,然后运行.因此,当您运行它时,

In javaScript Variables are moved to the top of script and then run. So when you run it will do

var myVar1;
alert(myVar1);
return false;

这是因为javascript并没有真正意义上的词法作用域.这就是为什么最好的做法是在变量的顶部声明所有变量,以防止由于提升引起的问题. JSLint会为此抱怨.

This is because javascript doesnt really have a true sense of lexical scoping. This is why its considered best practise to have all your variables declared at the top of the area they will be used to prevent hoisting causing a problem. JSLint will moan about this.

这是一篇很好的文章,对它进行了 http://www的解释. fullylygood.com/2010/2/JavaScript-Scoping-and-Hoisting

This is a good article that explains it http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

返回无效.如果您想做一个真实的吊装示例(摘自上面的链接),请

The return is invalid. If you want to do a true hoisting example (taken from the link above) do

var foo = 1; 
function bar() { 
    if (!foo) { 
        var foo = 10; 
    } 
    alert(foo); 
} 
bar();

这将提醒10

评论后编辑

以下是我的理解,我已经在某处阅读了它,但是找不到我阅读的所有资料,因此可以纠正.

Below is my understanding and I have read it somewhere but can't find all the sources that I read so am open to correction.

此警报是由于JavaScript JIT的不同而引起的. TraceMonkey( http://ejohn.org/blog/tracemonkey/)我相信它将采用JavaScript和进行快速静态分析,然后执行JIT,然后尝试运行它.如果失败了,那么显然是行不通的.

This Alerts thanks to the differences in the JavaScript JIT. TraceMonkey(http://ejohn.org/blog/tracemonkey/) I believe will take the JavaScript and do a quick static analysis and then do JIT and then try run it. If that fails then obviously nothing works.

V8不执行静态分析,而是移至JIT,然后运行某种方式.它更类似于python.如果您在Chrome的开发者控制台(Windows中为ctrl + shift + j)中运行脚本,则会引发错误,但也会运行以提醒您.

V8 doesnt do the static analysis and moves to the JIT then runs so something. Its more akin to python. If you run the script in the Developer console(ctrl+shift+j in windows) in Chrome it will throw an error but also run to give you the alert.

这篇关于为什么返回后的变量提升在某些浏览器上起作用,而在某些浏览器上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆