Reputation: 580
I have the following Javascript file:
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. In the HTML file, I import utils.js
like:
<script type="text/javascript" src="js/utils.js"></script>
and use the functions at the end of the body
like:
<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:
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! 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. I tried renaming the var just in case the declaration was replacing the function, but that didn't solve it either.
I am out of ideas of why this is not working. Can you find anything wrong?
EDIT: ANSWER by Dmitriy Loskutov
setMapHeight()
was redefining the global name because it didn't declare its variable with var
. I changed it to
function setMapHeight() {
var myAvailableHeight = availableHeight();
$("#map").outerHeight(myAvailableHeight);
}
and the error went away.
Thanks
Upvotes: 2
Views: 2072
Reputation: 288020
The local availableHeight
variable is hoisted to the top of its function, shadowing the global one.
Before you assign some value, it has the default undefined
value. But undefined
is not a function, so you can't call it.
Your code becomes something like
function availableHeight() { /* ... */ }
(function () {
var availableHeight = undefined; // Local variable hoisted to the top
availableHeight = availableHeight(); // TypeError (can't call undefined)
})();
Upvotes: 3