在JavaScript中缺少分号导致“'foo”未定义“ IE9中的错误 [英] Missing semi-colon in JavaScript causing "'foo' is undefined" error in IE9

查看:97
本文介绍了在JavaScript中缺少分号导致“'foo”未定义“ 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.

我有以下.js文件:

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

我还有以下HTML页面:

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>

当我在IE9中加载页面时,我收到错误'funcA'未定义。我可以通过以下任何一个来消除运行时错误:

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:


  • 打开兼容性在IE9中查看

  • 从页面中删除DOCTYPE

  • 在JavaScript之后和返回之前添加分号(即while( 1 = 1);返回0)

任何人都可以帮我理解这里究竟发生了什么吗?

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

推荐答案

不幸的是,JavaScript不要求你在任何地方明确地放置分号 - 但它会在内部为你提供这些分号。这通常会导致难以跟踪错误和意外行为。

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.

您的代码中的其他语法错误(正如其他人指出的那样), ; 需要的,当你放入那里时,事情就像你期望的那样工作。如果没有这样做,那么临时开发人员几乎不可能预测不同环境的行为如何不深入研究语言规范和JS引擎理解它们 - 假设有JS引擎本身的实现没有错误。 小件事,例如你是否有大括号(} )可能会有所不同

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.

这篇关于在JavaScript中缺少分号导致“'foo”未定义“ IE9中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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