接受带参数的javascript函数,作为参数(没有包装)?

时间:2014-04-30 14:27:19

标签: javascript

是否可以在没有周围的"包装"的情况下编写它。匿名函数()? 因此,基本上将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 FIDDLE http://jsfiddle.net/pST95/

5 个答案:

答案 0 :(得分:6)

事实证明你毕竟可以这样做:-)你可以使用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!

答案 1 :(得分:3)

  

是否可以在没有周围的“包装器”匿名函数()的情况下编写它?

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

在函数执行之前为函数预先设置参数的能力称为"Partial Application"。基本上,概念是您调用函数来生成新函数。新函数将使用正确的参数调用原始函数。

Vanilla JavaScript

Function.prototype.bind允许在上下文之后传递其他参数,然后在最终调用函数时使用该参数:

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

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

的jQuery

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

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

下划线

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

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

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

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

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

答案 2 :(得分:2)

您还可以使用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!");
}

答案 3 :(得分:0)

你的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作为建议。

答案 4 :(得分:-3)

这个怎么样

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


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

runner("myfunction('hello world');", 'Works!!!');
相关问题