Search code examples
javascriptfunctionfunction-calls

How to call a function that is inside another function javascript


I have two files as below:

trycapture.js (which has) trycapture() (which has) drawaggregate() definition
main.js from which I want to call drawaggregate();

trycapture.js

trycapture(){
... some code
function drawaggregate(){
... definition
   }
}

main.js

.. some variables
var try_obj = new trycapture();
try_obj.drawAggregate(emit_x1,emit_y1,emit_x2,emit_y2);

HTML

<head>
<script src="trycapture.js"></script>
<script src="js/main.js"></script>
</head>

How can I call that function. I tried creating an object right before calling drawaggregation() such as above:

I still get the error:

TypeError:try_obj.drawaggregate is not a function

Also, in index.html I made sure that I include trycapture.js before main.js How can I call that function?


Solution

  • Add

    this.drawaggregate = drawaggregate;
    

    after your function definition to make it a public method of the trycapture object.


    Overall, you will change your trycapture.js to the following:

    function trycapture(){
        ... some code
    
        // Locally accessible only
        function drawaggregate(){
            ... definition
        }
        this.drawaggregate = drawaggregate; // Makes it publicly accessible also
    }
    

    the drawaggregate() method can then be called like so:

    var try_obj = new trycapture();
    try_obj.drawaggregate();