javascript - 如何传递对带参数的函数的引用?

标签 javascript pass-by-reference anonymous-function

<分区>

Possible Duplicate:
How can I pre-set arguments in JavaScript function call? (Partial Function Application)

我需要能够传递对具有给定参数集的函数的引用

下面是一个不带参数传递引用的例子:

var f = function () {
    //Some logic here...
};

var fr = f; //Here I am passing a reference to function 'f', without parameters
fr(); //the 'f' function is invoked, without parameters

现在我需要做的是传递相同的 f 函数,但这次我需要将参数传递给引用。现在,我可以用一个匿名函数来完成它,并在新创建的函数中调用带有参数的 f 函数,如下所示:

var f = function () {
        //Some logic here...
    };

var fr = function (pars) {
    f(pars);
}; //Here I am creating an anonymous function, and invoking f inside it

fr({p : 'a parameter'}); //Invoking the fr function, that will later invoke the f function with parameters

但我的问题是,有没有一种方法可以将带有参数的 f 函数的直接引用传递给 fr,但不将其包含在匿名中功能?

我需要将什么分配给 fr 以使其无需参数即可调用 (fr()),以便 f(1,2,3)调用fr时执行?

[更新] 我关注了Jason Buntinghere 的回答关于 Partial Function 和他发布的 JavaScript 函数正是我要找的。这是解决方案:

function partial(func /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments).splice(1);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(this, allArguments);
  };
}

最佳答案

您所追求的是部分功能应用

不要被那些不了解柯里化(Currying)和柯里化(Currying)之间细微差别的人所愚弄,它们是不同的。

可以使用偏函数应用来实现,但不是柯里化(Currying)。这是来自 a blog post on the difference 的引述:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

这已经得到回答,请参阅此问题以获得答案:How can I pre-set arguments in JavaScript function call?

例子:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

再次,请参阅该问题以了解详细信息。

关于javascript - 如何传递对带参数的函数的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/373157/

相关文章:

javascript - 使用 Javascript 将阴影添加到 InDesign 中的所有选定项目

c++ - std::cout 不打印到控制台

javascript - 异步地理定位 API 和 jQuery 延迟对象

php - 如何在匿名函数中从数组中获取键?

javascript - 这个正则表达式模式/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/在Javascript中意味着什么?

javascript - 如果 CSS 文件禁用了属性,是否会下载图像?

javascript - 如何从客户端向数据库插入数据?

python - 将生成器附加到循环中的堆栈,生成器指向最终循环变量

Javascript 泛化多个对象的函数 (Raphael JS)

php - 为什么要使用匿名函数?