是否接受带参数的javascript函数作为参数(无包装器)

Accept javascript function with parameters, as a parameter (no wrapper)?

本文关键字:参数 包装 函数 javascript 是否      更新时间:2023-09-26

是否可以在不使用周围的"wrapper"匿名函数((的情况下编写此函数?所以,基本上把runner(function(){ myfunction('hello world') }, 'Works!!!')变成这个runner(myfunction('hello world'), 'Works!!!')

JS

function runner(func, something)
{
    alert(something);
    func();
}

function myfunction(value)
{
    alert("I should execute last!");
}

HTML

<button onclick="javascript: runner(function(){ myfunction('hello world') }, 'Works!!!')">Hit me</button>

JS FIDDLEhttp://jsfiddle.net/pST95/

事实证明,您毕竟可以做到这一点:-(您可以使用Function.prototype.bind创建一个新的函数对象,第一个参数作为当前上下文,其余参数作为实际函数的参数。

function runner(func, something) {
    console.log(something);
    func();
}
function myfunction(value) {
    console.log(value);
    console.log("I should execute last!");
}
runner(myfunction.bind(this, 'hello world'), 'Works!!!')

输出

Works!!!
hello world
I should execute last!

是否可以在没有"包装器"匿名函数((的情况下编写此函数?

要获得预设参数,您需要以某种方式使用包装器函数。不需要内联声明它是很方便的,但所有解决方案仍然需要使用包装器函数。

在函数执行之前为其预设参数的能力称为"部分应用"。基本上,概念是调用一个函数来生成一个新函数。新函数将使用正确的参数调用原始函数。

香草JavaScript

Function.prototype.bind允许在上下文之后传递额外的参数,然后在最终调用函数时使用这些参数:

runner(myfunction.bind(window, 'hello world'), 'Works!!!');

当然,IE8及以下版本不支持此功能,因此需要使用polyfill来启用此行为。

jQuery

$.proxy是jQuery库中的跨浏览器兼容版本:

runner($.proxy(myfunction, window, 'hello world'), 'Works!!!');

Undercore

_.bind是Undercorejs库中的跨浏览器兼容版本:

runner(_.bind(myfunction, window, 'hello world'), 'Works!!!');

但是,如果您希望在生成包装器时避免绑定上下文,下划线还提供了一个真正的分部应用程序函数。

_.partial将仅绑定参数,并允许在执行函数时确定上下文:

runner(_.partial(myfunction, 'hello world'), 'Works!!!');

您还可以使用apply或call,这样:

<button onclick="javascript: runner(myfunction,'hello world', 'Works!!!')">Hit me</button>
function runner(func, args, something)
{
    alert(something);
    func.call(this, args);
}
function myfunction(value)
{
    alert("I should execute last!");
}

runner函数需要一个不带参数的函数,因为它是这样运行的:

func();

所以你不能真的像这样把myfunction传给它:

runner(myfunction, 'Works!!!')

因为你没有办法给myfunction一个参数(从技术上讲,它确实有效,因为你的myfunction无论如何都不使用这个参数(。但如果你尝试这个:

runner(myfunction('hello world'), 'Works!!!')

然后,您所要做的就是直接调用myfunction,并将返回的值(在本例中为undefined(作为参数发送到runner,如果您查看控制台,您应该会看到一个错误:TypeError: undefined is not a function

所以不需要,您需要原始调用的包装器,或者您可以按照您的建议使用Function.prototype.bind