从另一个JS文件访问对象时未捕获的ReferenceError

时间:2011-02-06 20:30:41

标签: javascript

我的Web应用程序中有各种JS库,它们在我的主JS文件(main.js)之前加载。其中一个库是jshashtable,但是当我尝试在main.js中创建一个新的Hashtable对象时,Google Chrome和Firefox会抛出一个ReferenceError,抱怨该变量不存在。

这是< head>申请:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
 <script type="text/javascript" src="/static/jquery-1.4.4.min.js"></script>
 <script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
 <script type="text/javascript" src="/static/main.js"></script>

以下是main.js中的问题行:

posts = new Hashtable();

这一行位于一个名为init的函数中,当页面加载完成时调用该函数(使用jquery $(document).ready()函数)。

为什么Hashtable不是全球性的?谷歌地图和jquery对象没有这样的问题。可以在Google code上看到jshashtable的来源。

1 个答案:

答案 0 :(得分:2)

更新回答:问题是您在script标记中输入了拼写错误:

<script type="text/javacsript" src="/static/jshashtable-2.1.js"></script>
<!--                   ^^---- here (the letters are transposed)       -->

我无法理解为什么你会遇到问题并决定实际复制并粘贴你的脚本标签并在我的机器上完全复制结构。事情停止了,我的世界逆时针倾斜了3°,直到我终于盯着他们看足够长的时间。

如果jshashtable代码确实在/static/jshashtable-2.1.js并且您的服务器正在提供服务(仔细检查开发工具中Chrome浏览器的资源选项卡),我看不出任何理由。您的脚本顺序正确,jshashtable的文档使用全局Hashtable显示(您提供的代码链接清楚地显示它创建了一个)。


编辑:我刚刚在自己的服务器上复制了相同的结构(相同的脚本,相同的顺序,使用jQuery(document).ready(function() { ... });),并没有遇到这个问题。我可以创建一个Hashtable并使用它的功能。

我的HTML:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type='text/javascript' src='jquery-1.4.4.js'></script>
<script type='text/javascript' src='jshashtable-2.1.js'></script>
<script type='text/javascript' src='main.js'></script>
</head>
<body>
</body>
</html>

我的main.js

jQuery(document).ready(function() {
    try {
        var ht = new Hashtable();
        display("typeof ht = " + typeof ht);
        display("ht.size() = " + ht.size());
    }
    catch (e) {
        display("Exception: " + e);
    }

    function display(msg)
    {
        $("<p>").html(msg).appendTo(document.body);
    }
});

唯一的区别是我没有使用/static前缀,我绝对肯定没有区别。

相关问题