简体   繁体   中英

Missing semi-colon in JavaScript causing “'foo' is undefined” error in IE9

I just spent about four hours tracking down this problem. I know what is causing it but don't know why and the "why" is bugging me.

I have the following .js file:

function funcA() {
}
function funcB() {
    do {
    } while (1 == 1) return 0
}

I also have the following HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title></title>
    <script src="JScript1.js" type="text/javascript"></script>
</head>
<body>
    <script type="text/javascript">
        new funcA();
    </script>
</body>
</html>

When I load the page in IE9 I get an error that "'funcA' is undefined." I can get rid of the run-time error by do any one of the following:

  • Turning on Compatibility View in IE9
  • Removing the DOCTYPE from the page
  • Adding a semi-colon after the while and before the return in the JavaScript (ie while (1 = 1); return 0)

Can anyone help me understand what exactly is going on here?

Unfortunately, JavaScript does not require you to explicitly put in semi-colons everywhere that there should be one - but it will internally put those in for you. This can often lead to hard to trace bugs and unexpected behavior.

Among other syntax errors in your code (as others have pointed out), the ; after the while in a do-while is required and when you put in there, things work as you expect them to. When this isn't done, it's pretty much impossible for the casual developer to predict how different environments will behave without digging deep into the specs of the language and the JS engine and understanding it all - assuming there are no bugs in the implementation of the JS engine itself. Little things such as whether you have braces ( { and } ) in the same line or not can make a difference .

From my reading of the ECMAScript spec , IE's behavior is correct . See sections:

  • 7.9.1 Rules of Automatic Semicolon Insertion (which describes the cases in which a semi-colon may be inserted, none of which apply)

  • 12.6.1 The do-while Statement (which shows that your code is not a valid production of the form do Statement while ( Expression );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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