How can get a list of the functions in a javascript file?

后端 未结 4 1203
终归单人心
终归单人心 2021-01-20 14:18

I\'m trying to cobble together a php style include function for javascript. The route I\'m taking is through a XMLHttpRequest. The included file will load, but the functions

相关标签:
4条回答
  • 2021-01-20 14:40

    OrbMan pointed me in the right direction on this one, but the solution to this particular method of including Javascript files requires the functions be defined differently; like this

    window.myFunction = function(){ 
    
        alert("Hey There!") 
    
    }
    

    A potential upside to this is that any functions in the included file that are declared the normal way are encapsulated so they are only available to the window.functions from that file... as far as I can tell.

    0 讨论(0)
  • 2021-01-20 14:43

    It's simple enough to use the DOM to add the required script:

    function include(jsFile)
    {
        var sEl  = document.createElement("script");
        sEl.type = "text/javascript";
        sEl.src  = jsFile;
        document.getElementsByTagName("head").appendChild(sEl);
    }
    

    Browsers will even download this file asynchronously, and script elements have an onload event that works in most (all?) popular browsers so you can also add a callback function if you like. The obvious downside is that functions wouldn't become available to the current script until the file is downloaded and parsed.

    0 讨论(0)
  • 2021-01-20 14:46

    Instead of loading the JavaScript file via AJAX, why not create a <script> tag and insert that into the page? That will allow the JavaScript to be parsed in the global scope. Take a look at how Scriptaculous' require function works

    0 讨论(0)
  • 2021-01-20 14:51

    Change the way you declare your functions and it should solve the scoping issue. Instead of:

    function add(a, b) 
    {                     
        return a + b;
    } 
    

    do this:

    var add = function(a, b) 
    {                     
        return a + b;
    }   
    
    0 讨论(0)
提交回复
热议问题