Why is my JavaScript function sometimes “not defined”?

后端 未结 13 1805
逝去的感伤
逝去的感伤 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:45

    Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)

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

    This can happen when using framesets. In one frame, my variables and methods were defined. In another, they were not. It was especially confusing when using the debugger and seeing my variable defined, then undefined at a breakpoint inside a frame.

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

    This doesn't solve your original problem, but you could always replace the call to copyArray() with:

    __args = Array.prototype.slice.call(arguments);
    

    More information available from Google.

    I've tested the above in the following browsers: IE6, 7 & 8B2, Firefox 2.0.0.17 & 3.0.3, Opera 9.52, Safari for Windows 3.1.2 and Google Chrome (whatever the latest version was at the time of this post) and it works across all browsers.

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

    A syntax error in the function -- or in the code above it -- may cause it to be undefined.

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

    Solved by removing a "async" load:

      <script type="text/javascript" src="{% static 'js/my_js_file.js' %}" async></script>
    

    changed for:

      <script type="text/javascript" src="{% static 'js/my_js_file.js' %}"></script>
    
    0 讨论(0)
  • 2020-12-24 01:51

    I'm afraid, when you add a new method to a Function class (by prtotyping), you are actually adding it to all declared functions, AS WELL AS to your copyArray(). In result your copyArray() function gets recursivelly self-referenced. I.e. there should exist copyArray().bind() method, which is calling itself.

    In this case some browsers might prevent you from creating such reference loops and fire "function not defined" error.

    Inline code would be better solution in such case.

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