Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object literal method: Recursive call

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.

like image 642
user972959 Avatar asked Jan 25 '12 16:01

user972959


2 Answers

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/

like image 177
user123444555621 Avatar answered Nov 14 '22 21:11

user123444555621


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)

like image 5
Adam Rackis Avatar answered Nov 14 '22 21:11

Adam Rackis