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

前端 未结 5 1244
执笔经年
执笔经年 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 12:44

    Section 12.9 (page 75) of ECMA-262 edition 3 states:

    An ECMAScript program is considered syntactically incorrect if it contains a return statement that is not within a FunctionBody.

    That is, a return outside of a function is a syntax error. If a syntax error occurs, no code is run. Think about your example as if you had written:

    alert(myVar1);
    return false;
    syntax error))))))))))))))))));
    

    In addition, section 16 (page 157) states:

    An implementation may treat any instance of the following kinds of runtime errors as a syntax error and therefore report it early:

    • Improper uses of return, break, and continue.

    Firefox's engine et. al. (i.e. those JavaScript implementations which allow return in the global scope) may be conforming, assuming the following clause (in the same section) allows for implementation definition of return in the global scope:

    An implementation shall report all errors as specified, except for the following:

    • An implementation may provide additional types, values, objects, properties, and functions beyond those described in this specification. This may cause constructs (such as looking up a variable in the global scope) to have implementation-defined behaviour instead of throwing an error (such as ReferenceError).

提交回复
热议问题