views:

74

answers:

2

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?

+3  A: 

In the first snippet, myfunc only exists with in the scope of the anonymous function you've defined. In the second snippet, myfunc is not within any visible scope. Finally, in the third snippet when you define myfunc at the top level, it's available at the global scope so any other part of your javascript will be able to call it successfully.

If you find yourself still having trouble understanding variable scope in Javascript, you might want to try reading through some of the results for "javascript scope" on Google for a more thorough explanation.

Mark Rushakoff
+6  A: 

It's a matter of scope.

In

$(function() {
    myfunc() {
        alert('inside myfunc');
    }
    alert('outside myfunc');
    myfunc(); //this successfully runs myfunc()
});

it is only available inside the anonumous function (function() { }), so also if you were to call it outside of this, but inside the same js file it would be unavailable.

While if you declare it using

myfunc = function () { ... }

myfunc is a global variable and the function is available everywhere.

Mario Menger
It should be noted that the anonymous function wrapper `function() { ... }` is used primarily for exactly this purpose! If you want to define a function globally, just leave it outside the wrapper. If you have to write a global variable inside a local scope, it is good manners (and required in ECMA262-5 Strict Mode) to declare `var myvar;` in global scope, outside the wrapper.
bobince