如何调用另一个函数中的函数 javascript

How to call a function that is inside another function javascript

我有两个文件如下:

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>

如何调用该函数。我尝试在调用 drawaggregation() 之前创建一个对象,如上所示:

我仍然得到错误:

TypeError:try_obj.drawaggregate is not a function

此外,在 index.html 中,我确保在 main.js 之前包含 trycapture.js 如何调用该函数?

添加

this.drawaggregate = drawaggregate;

在您的函数定义之后使其成为 trycapture 对象的 public 方法。


总体而言,您将 trycapture.js 更改为以下内容:

function trycapture(){
    ... some code

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

然后可以像这样调用 drawaggregate() 方法:

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