Why variable hoisting after return works on some browsers, and some not?

前端 未结 5 1276
执笔经年
执笔经年 2020-11-22 12:11
alert(myVar1);
return false;
var myVar1;

Above code throws error in IE, FF and Opera stating that return statement has to come in the function. But

5条回答
  •  借酒劲吻你
    2020-11-22 13:01

    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;
    

    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.

    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();
    

    This will alert 10

    EDIT AFTER COMMENT

    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.

    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 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.

提交回复
热议问题