JavaScript Object literal method: Recursive call
Asked Answered
F

3

8

Is it possible to call recursively a method from an object literal?

For example:

(function () {
    'use strict';
    var abc = ['A', 'B', 'C'],
        obj = {
            f: function () {
                if (abc.length) {
                    abc.shift();
                    f(); // Recursive call
                }
            }
        };

    obj.f();
}());

Error: 'f' was used before it was defined.

Thanks.

Fachanan answered 25/1, 2012 at 16:51 Comment(0)
C
17

You can, by using a named function expression:

        f: function myself() {
            if (abc.length) {
                abc.shift();
                myself(); // Recursive call
            }
        }

A must-read: http://kangax.github.com/nfe/

Christianchristiana answered 25/1, 2012 at 17:42 Comment(2)
This should be the chosen answer. Thanks for the link too.Tired
What exactly does making it a named function do that circumvents the erorr? Create it's own closure?Premonition
I
5

f is a method on your object. As a result, when you're in f, this will be the object to which f is attached. So to recursively call f, use this.f()

f: function () {
    if (abc.length) {
        abc.shift();
        this.f(); // Recursive call
    }
}

Just note that inside of f, this will only be the current object if f is invoked as a method: obj.f();

If you do somethinig like: obj.f.call(lala);, then this will now be lala. And if you do something like:

var func = obj.f;
func();

Now this is the global object inside of f (or undefined in strict mode)

Ikon answered 25/1, 2012 at 17:1 Comment(3)
this may or may not point to obj depending on how f is called. Better make this clear before it bites the guy later.Affinity
@MattiVirkkunen - indeed - edited. Thanks for the tip, and enjoy your new badges :)Ikon
Yay!Affinity
A
1

There's no variable called f defined anywhere in your code. Use obj.f() (or this.f if you know this points to where it should).

Affinity answered 25/1, 2012 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.