最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

recursion - JavaScript Object literal method: Recursive call - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jan 25, 2012 at 16:51 user972959user972959 3811 gold badge4 silver badges5 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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/

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)

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).

发布评论

评论列表(0)

  1. 暂无评论