1

How can I achieve that in Javascript?

exports.functions = {
    my_func: function (a) {
        my_func(a);
    }
}
3
  • 6
    Name it! Commented Feb 3, 2015 at 20:01
  • @bergi what about this.my_func() ? Commented Feb 3, 2015 at 20:09
  • 1
    @RoyiNamir: Yeah, that'll work as well when the function is guaranteed to be always called as a method on functions. Commented Feb 3, 2015 at 20:11

2 Answers 2

7

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

in the article Bergi pointed to in the comments on the question.. that 'optional' name isn't implemented properly in some interpeters.. not sure if JScript compatibility is worth consideration though.
@BrettCaswell Only IE had the problem AFAIK - but a function expression name still works in IE. In some IE versions the scope would just bleed to a binding in the current context as well which is a side-effect that can be largely ignored.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.