我对JavaScript还是很陌生,我正在按照一个教程尝试使用全局范围。
在本教程中,我有3个文件:
1)index.htm:
<html>
<head></head>
<body>
<h1>HELLO WORLD !!!</h1>
<script src="app.js"></script>
<script src="utility.js"></script>
</body>
</html>
如您所见,我包含2个JavaScript文件。
2)app.js:
var person = 'Torny'; // When I call the logPerson() function this line override the person variable value into the global stack
//console.log(person);
logPerson();
3)utility.js在其中限定的logPerson()定义为函数的app.js文件:
var person = 'Steve';
function logPerson() {
console.log(person);
}
好的,所以我期望以下行为:
进入app.js文件中设置字符串“托尼”作为价值的人变量,呼叫的logPerson()函数声明为utility.js文件,所以在控制台打印“托尼”。
问题是,当我尝试在FireFox中打开index.htm文件时,进入FireBug控制台,取而代之的是'Tony'值,我得到此错误消息:
ReferenceError: logPerson is not defined
如此看来,从app.js文件,它无法看到logPerson()被定义为功能utility.js文件并导入。
为什么?我想念什么?怎么了?
在javascript中,文件的顺序很重要。您需要先加载定义功能的脚本,然后才能使用它。切换2个<script>
标签
<body>
<h1>HELLO WORLD !!!</h1>
<script src="utility.js"></script>
<script src="app.js"></script>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句