Why is my JavaScript function sometimes “not defined”?

后端 未结 13 1806
逝去的感伤
逝去的感伤 2020-12-24 01:18

I call my JavaScript function. Why do I sometimes get the error \'myFunction is not defined\' when it is defined?

For example. I\'ll occasionally g

相关标签:
13条回答
  • 2020-12-24 01:52

    Use an anonymous function to protect your local symbol table. Something like:

    (function() {
        function copyArray(pa) {
            // Details
        }
    
        Function.prototype.bind = function ( po ) {
            __args = copyArray( arguments );
        }
    })();
    

    This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.

    0 讨论(0)
  • 2020-12-24 01:53

    If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object.

    Test it in multiple browsers to find out.

    0 讨论(0)
  • 2020-12-24 01:57

    My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.

    0 讨论(0)
  • 2020-12-24 02:06

    It shouldn't be possible for this to happen if you're just including the scripts on the page.

    The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.

    0 讨论(0)
  • 2020-12-24 02:06

    I think your javascript code should be placed between tag,there is need of document load

    0 讨论(0)
  • 2020-12-24 02:09

    I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it.

    What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way:

    <SCRIPT src="mycode.js"/>
    

    (That is, without the closing tag.)

    I had to redeclare this block in the following way.

    <SCRIPT src="mycode.js"></SCRIPT>
    

    And then what followed worked fine... weird huh?

    0 讨论(0)
提交回复
热议问题