可变吊装 [英] Variable hoisting

查看:121
本文介绍了可变吊装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.adequatelygood.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天全站免登陆