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

时间:2016-06-10 19:23:18

标签: javascript function function-calls

我有两个文件如下:

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不是函数

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

1 个答案:

答案 0 :(得分:1)

添加

this.drawaggregate = drawaggregate;
在函数定义之后

使其成为trycapture对象的公共方法。

总的来说,您将把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();