myfunc() runs successfully when called from within the same js file. but it is undefined (Firebug) when called from an HTML page:
JS file:
$(function() {
myfunc() {
alert('inside myfunc');
}
alert('outside myfunc');
myfunc(); //this successfully runs myfunc()
});
HTML:
<script>
$(function() {
myfunc(); //this doesn't run myfunc(). It's undefined
});
</script>
But when I change myfunc() declaration to:
myfunc = function () { ... }
It’s no longer undefined, and runs successfully.
Sorry for this very noob question, but what just happened? Why did it work when I changed the way I declared the function?
It’s a matter of scope.
In
it is only available inside the anonymous function (
function() { }), so it would also be unavailable if you were to call it outside of the anonymous function but inside the same js file.While if you declare it using
myfunc is a global variable and the function is available everywhere.