如何显式引用全局函数

How to explicitly reference global functions?

本文关键字:函数 全局 引用 何显式      更新时间:2023-09-26

我如何引用全局函数,在这种情况下,使用其名称将引用例如局部变量?

以这个简单的递归为例:

function foobar(foobar) {
    return foobar(foobar+1); //<- error in this line
}

这将产生错误"foobar 不是函数",因为相同的名称被定义为参数。如何在不重命名函数或参数的情况下显式引用函数?我试过了

function foobar(foobar) {
    return Window.foobar(foobar+1);
}

没有成功。

正如

@Juhana所说,这将起作用,你会得到一个Exception: InternalError: too much recursion如预期的那样

function foobar(foobar) {
    return window.foobar(foobar+1);
}
foobar(3);

可以使用命名函数表达式。在函数中使用函数名称(recursive)。从外部将函数分配给名为 foobar 的变量:

var foobar = function recursive(foobar) {
    return recursive(foobar + 1);
}
foobar(5);