从类调用函数

Calling function from class

本文关键字:函数 调用      更新时间:2023-09-26

在我正在处理的混合移动应用程序中,我无法从外部类调用函数或方法。我将代码简化为:

var hub_api = (function() {
    function send() {
        console.log('hub api called');
    };
    return {
        send: function() {
            send();
        }
    };
});

叫这样称呼:

(function() {
    function register_event_handlers() {
        $(document).on(" touchend", "#btntest", function(evt) {
            hub_api.send();
            alert('pressed test button');
        });
    }
    document.addEventListener("app.Ready", register_event_handlers, false);
})();

实际代码在另一个项目中工作正常。脚本都包含如下:

<script type="application/javascript" src="js/helpers/api.js"></script>
<script type="application/javascript" src="js/helpers/testclass.js"></script>

运行应用将返回hub_api is not defined 。我完全被难住了。任何帮助,不胜感激。

编辑:我发现当我将hub_api功能放入应用程序中时.js它按预期工作,但在包含在单独的 api.js 脚本中时仍然无法工作。脚本按正确的顺序调用。

尝试在主function()中定义hub_api,如下所示:

(function() {
    var hub_api = (function() {
        function send() {
            console.log('hub api called');
        };
        return {
            send: function() {
                send();
            }
        };
    })();
    function register_event_handlers() {
        $(document).on(" touchend", "#btntest", function(evt) {
            hub_api.send();
            alert('pressed test button');
        });
    }
    document.addEventListener("app.Ready", register_event_handlers, false);
})();