Javascript window [“ functionName”](参数)返回“不是函数” TypeError

时间:2018-11-24 12:24:36

标签: javascript jquery ajax eval

我正在尝试根据应用程序中当前处于活动状态的选项卡运行AJAX函数。当我在某些事件后调用该函数时,一切正常,但是我无法动态地使用字符串变量来调用该函数。

遵循此答案:https://stackoverflow.com/a/359910/5950111我刚刚收到一个TypeError,描述了Im调用的对象不是函数。

这是我的ajax函数:

function home_tab_fetchMore(items_count) {
    let request = new XMLHttpRequest();
    let output = []
    request.open('GET', `feedstream/${items_count}`);
    request.onload = function () {
        if (request.status === 200 && request.responseText != '') {
            let new_items = JSON.parse(request.responseText);
            for (let i = 0; i < new_items.length; i++) {
                let item = new_items[i];
                let event_id = feed_stream_row.children.length + 1;
                let feed_item = htmlToElement(`
                        <div class="grid-item" id="eventcard_${event_id}">
                        <div class="card-header">Featured</div>
                        <div class="card-body">
                        <h5 class="card-title">${item.fields['title']}</h5>
                        <p class="card-text">${item.fields['appointment']}
                        <br>
                        ${dummy_text.sentence(5, 40)}
                        </p>
                        </div>
                        </div>
                    `);
                // appending new item to DOM and updating masonry laytout
                feed_stream_row.appendChild(feed_item);
                msnry.appended(feed_item);
                output.push(feed_item);
            }
        } else {
            console.log('no response!');
        }
    };
    request.send();
    return output;
};

这是呼叫者事件:

$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
        var fnstring = `${current_active_tab().id}_fetchMore`;
        var fn = window[fnstring]

        console.log(typeof(fnstring)) // returns: string type
        console.log(fnstring) // returns: home_tab_fetchMore without quotes
        console.log(fn) // returns: undefined

        fn(2) // returns: Uncaught TypeError: fn is not a function

        // however, this line works just as expected:
        home_tab_fetchMore(2)
    };
});

还有我无法理解的TypeError附加行:

Uncaught TypeError: fn is not a function
at main.js:128
at dispatch (jquery-3.3.1.slim.min.js:2)
at v.handle (jquery-3.3.1.slim.min.js:2)

我先感谢任何建议和指导,谢谢。

1 个答案:

答案 0 :(得分:2)

function home_tab_fetchMore(items_count) {}

除非调用window对象,否则以上函数定义将不可用。而是使用函数表达式(在定义函数表达式之前不能使用它们)。

home_tab_fetchMore = function() {} OR
window.home_tab_fetchMore = function() {}