A
A
Anton Shamanov2019-04-03 14:14:03
JavaScript
Anton Shamanov, 2019-04-03 14:14:03

How to recursively call a function given in a variable?

Simplified function code:

var func = function(items, errors) {
    if (items.length) {
        $.post(
            '/items/add/',
            {id: items.pop()},
            function (response) {
                if (typeof response.error != 'undefined') {
                    errors.push(response.error);
                } else {
                    // как осуществить вызов функции из переменной func (рекурсивный вызов)? 
                    ...(items, errors);
                }
            },
            'json'
        );
    } elseif (errors.length) {
        alert(errors.join(' '));
    }
};

func(new_items, []);

I am not familiar with JS, so the only thing that came to my mind was to pass the variable that stores the function as one of the parameters when calling, i.e.:
var func = function(fself, items, errors) {
    ...
    fself(fself, items, errors);
    ...
};
func(func, new_items, []);

in extreme cases, you can specify the name of the function:
function func(items, errors) {
    ...
    func(items, errors);
    ...
}
func(new_items, []);

The question is, is it possible to somehow recursively call such an anonymous function without explicitly passing this function to itself?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2019-04-03
@Vlad_IT

Do you mean so?

var func = function funcSelf(items, errors) { 
     // тут всякий код
     funcSelf(); // вызываем, используя имя funcSelf, которое доступно только внутри функции
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question