-1

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?

Arihant
  • 3,847
  • 16
  • 55
  • 86

1 Answers1

1

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();
FactoryAidan
  • 2,484
  • 1
  • 13
  • 13
  • I am able to call the function even without the object now. Is that normal? – Arihant Jun 10 '16 at 19:57
  • Yes, it's normal. It depends on many things and more than can fit in this comment box. So explaining here could be incomplete and confusing. EXAMPLE1: If you happen to call your `new trycapture()` from inside an anonymous function such as an `onload` event listener, then `this` inside of `trycapture` would refer to the `window` object instead. Thus, `drawaggregate` would become a global window function callable from anywhere. EXAMPLE2: If you are inside the `trycapture` function namespace, you are allowed to(and should) call `drawaggregate` as a local function instead of a method of an object. – FactoryAidan Jun 10 '16 at 21:57