[英]Javascript function from external file not found
I have the following Javascript file: 我有以下Javascript文件:
function availableHeight() {
var windowHeight = window.innerHeight;
var headerHeight = $(".page-header").innerHeight();
var marginPaddingEtc = 105;
return windowHeight - marginPaddingEtc - headerHeight;
}
function setMapHeight() {
availableHeight = availableHeight();
$("#map").outerHeight(availableHeight);
}
which is named utils.js and is placed inside a js/
folder relative to my HTML file. 名为utils.js,相对于我的HTML文件放置在js/
文件夹中。 In the HTML file, I import utils.js
like: 在HTML文件中,我导入utils.js
像这样:
<script type="text/javascript" src="js/utils.js"></script>
and use the functions at the end of the body
like: 并在body
末尾使用以下功能:
<script>
$(document).ready(function () {
$("#menu").load("demo_nav.html", function() {
setMapHeight();
var availableHeight = availableHeight();
console.log(availableHeight);
});
});
</script>
When opening the page in Firefox 44.0.2, I get the following output in the console: 在Firefox 44.0.2中打开页面时,我在控制台中得到以下输出:
TypeError: availableHeight is not a function
var availableHeight = availableHeight();
What surprises me the most is the fact that setMapHeight() is being found and availableHeight() is not, even though they are in the same file! 最让我感到惊讶的是,即使找到了setMapHeight()而没有找到availableHeight(),即使它们在同一个文件中! Since one is found, I know the issue is not with the import. 既然找到了,我知道问题不在于导入。 I am calling the functions in $(document).ready() so everything should be loaded by then. 我在$(document).ready()中调用函数,因此届时应该加载所有内容。 I tried renaming the var just in case the declaration was replacing the function, but that didn't solve it either. 我尝试重命名var,以防万一声明正在替换函数,但这也没有解决。
I am out of ideas of why this is not working. 我不知道为什么这不起作用。 Can you find anything wrong? 你能找到什么错吗?
EDIT: ANSWER by Dmitriy Loskutov 编辑:德米特里·洛斯科托夫(Dmitriy Loskutov)的答案
setMapHeight()
was redefining the global name because it didn't declare its variable with var
. setMapHeight()
正在重新定义全局名称,因为它没有使用var
声明其变量。 I changed it to 我将其更改为
function setMapHeight() {
var myAvailableHeight = availableHeight();
$("#map").outerHeight(myAvailableHeight);
}
and the error went away. 错误消失了。
Thanks 谢谢
The local availableHeight
variable is hoisted to the top of its function, shadowing the global one. 局部availableHeight
变量被提升到其函数的顶部,从而遮盖了全局变量。
Before you assign some value, it has the default undefined
value. 在分配一些值之前,它具有默认的undefined
值。 But undefined
is not a function, so you can't call it. 但是undefined
不是函数,所以您不能调用它。
Your code becomes something like 您的代码变成类似
function availableHeight() { /* ... */ }
(function () {
var availableHeight = undefined; // Local variable hoisted to the top
availableHeight = availableHeight(); // TypeError (can't call undefined)
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.