匿名函数——我的常年承办人

Anonymous functions - my perennial undertaker

我在 Java 中使用了匿名函数,现在在 JavaScript 中使用了匿名函数,但我仍然不明白一件事。

使用Java脚本,我们可能会有如下代码:

doSomething('omg',function(mark){
    console.log(mark);
});

function doSomething(printthis,callback){
    console.log(printthis);
    callback();
}

所以我们将 'omg' 和一个匿名函数传递给 doSomething 函数。

然而,parameter/argument 'mark' 从何而来?我们如何将标记参数传递给这个匿名函数?我发誓我看到过一次又一次这样做,但我不知道标记参数来自哪里。

在哪里?

mark 参数将来自 callback() 的调用;但是,您在那里没有指定任何参数,因此 mark 将是 undefined。如果你写 callback(printthis + " in callback"),那么你会在控制台中收到 "omg in callback"

// using document.write() so it shows up on the snippet. Don't do this at home. :)

doSomething('omg',function(mark){
    document.write("<p>" + mark + "</p>");
});

function doSomething(printthis,callback){
    document.write("<p>" + printthis + "</p>");
    callback(printthis + " in callback");
}

最好的方法是使用 bind,但请记住需要设置 this,否则为空。

doSomething('omg',function(mark){
    console.log(mark);
}.bind(null, 'test'));

function doSomething(printthis,callback){
    console.log(printthis);
    callback();
}

jsfiddle

这也可以通过包装另一个匿名函数来实现。

doSomething('omg',(function(mark){
    return function(){
        console.log(mark);
    }
})('test'));

function doSomething(printthis,callback){
    console.log(printthis);
    callback();
}

jsfiddle

您不知道如何将参数传递给用户定义的函数:

function doSomething(printThis, callback, context){
  var c = context || this; // if you need to bind the context of callback
  callback.call(c, printThis); // your callback is passed printThis
}
doSomething('omg', function(mark){
  console.log(mark);
});

您实际上在执行回调的函数中定义了传递给用户定义函数的参数。