JavaScript 对象字面量方法:递归调用

发布于 2024-12-28 19:47:05 字数 383 浏览 5 评论 0原文

是否可以从对象字面量递归调用方法?

例如:

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

    obj.f();
}());

错误:'f' 在定义之前就被使用了。

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彩扇题诗 2025-01-04 19:47:05

您可以通过使用命名函数表达式

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

必读:http:// kangax.github.com/nfe/

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/

眼泪都笑了 2025-01-04 19:47:05

f 是对象上的一个方法。因此,当您处于 f 中时,this 将成为 f 所附加的对象。因此,要递归调用 f,请使用 this.f()

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

请注意,在 f 内部,this 只会如果 f 作为方法调用,则为当前对象: obj.f();

如果执行类似以下操作: obj.f.call(lala);,那么 this 现在将是拉拉。如果您执行以下操作:

var func = obj.f;
func();

现在 thisf 内部的全局对象(或在严格模式下未定义)

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)

各自安好 2025-01-04 19:47:05

代码中的任何位置都没有定义名为 f 的变量。使用 obj.f() (如果您知道 this 指向它应该指向的位置,则使用 this.f)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文