Adrien Neveu
Adrien Neveu

Reputation: 827

How to call recursively a function stored in a variable in Javascript

How can I achieve that in Javascript?

exports.functions = {
    my_func: function (a) {
        my_func(a);
    }
}

Upvotes: 1

Views: 66

Answers (2)

Barmar
Barmar

Reputation: 780879

A function expression can have an optional name after the function keyword. The scope of this name is just the function body, and allows it to be called recursively:

exports.function = {
    my_func: function this_func(a) {
        this_func(a);
    }
}

You can also use its full name:

exports.function = {
    my_func: function(a) {
        exports.function.my_func(a);
    }
}

Upvotes: 7

atrifan
atrifan

Reputation: 172

This is not quite ok as a standard, but you can easily achieve this like:

var foo = function(a) {
    foo(a);
}
exports.functions = {my_func: foo};

Your code does not work because in this case the hoisting is not done ok(well it's done ok) but not for what you need.

Upvotes: 0

Related Questions