Why is my JavaScript function sometimes "not defined"?
<p>I call my JavaScript function. Why do I <em>sometimes</em> get the error 'myFunction is not defined' when it <em>is</em> defined?</p>

<p>For example. I'll occasionally get 'copyArray is not defined' even in this example:</p>

<pre><code>function copyArray( pa ) {
    var la = [];
    for (var i=0; i &lt; pa.length; i++)
        la.push( pa[i] );
    return la;
}

Function.prototype.bind = function( po ) {
    var __method = this;
    var __args = [];

    // Sometimes errors -- in practice I inline the function as a workaround.
    __args = copyArray( arguments );

    return function() {
        /* bind logic omitted for brevity */
    }
}
</code></pre>

<p>As you can see, copyArray is defined <em>right there</em>, so this can't be about the order in which script files load.</p>

<p>I've been getting this in situations that are harder to work around, where the calling function is located in another file that <em>should</em> be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.</p>

<p>It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.</p>

<p>@Hojou: That's part of the problem.  The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.</p>

<p>@James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error.</p>

<p>@David: The script in this case resides in an external file that is referenced using the normal &lt;script src="file.js"&gt;&lt;/script&gt; method in the page's head section.</p>

<p>@Douglas: Interesting idea, but if this were the case, how could we <em>ever</em> call a user-defined function with confidence? In any event, I tried this and it didn't work.</p>

<p>@sk: This technique has been tested across browsers and is basically copied from the <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="nofollow">Prototype</a> library.</p>
