在JavaScript中传递匿名函数中的参数

在JavaScript中传递匿名函数中的参数

本文介绍了在JavaScript中传递匿名函数中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会看到用参数编写的JavaScript,前提是已经有一个设置值或者是一个带方法的对象。以此jQuery示例为例:

Sometimes I see JavaScript that is written with an argument provided that already has a set value or is an object with methods. Take this jQuery example for instance:

$(".selector").children().each(function(i) {
    console.log(i);
});

当记录 i 时,你会得到当查看jQuery 每个方法中的selectors子项时, i 中的任何值都在该迭代中。

When logging i, you would get the value of whatever i is in that iteration when looking at the selectors children in the jQuery each method.

以此Node.js为例:

Take this Node.js example:

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

您可以在此处看到请求回复正在传递,它们包含自己可以采取行动的方法。

You can see here that request and response are being passed and they contain their own methods that can be acted on.

对我来说,这看起来像是将函数传递给 createServer 函数,其中两个参数已经附加了方法。

To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them.

我的问题是多部分一:


  1. 这些参数来自哪里?

  2. 如果这些只是一个非函数函数,它们如何接收可以像其他函数一样执行的参数?

  3. 如何创建可以执行的函数像这样拿我自己的论点?

  4. 这是否使用闭包的力量?

  1. Where do these arguments come from?
  2. If these are just anon functions, how do they receive arguments that can be acted on like other functions?
  3. How do I create functions that can take my own arguments like this??
  4. Does this use the power of closures??


推荐答案

没有。他们将一个函数传递给 createServer ,它接受两个参数。稍后将使用调用者输入的任何参数调用这些函数。例如:

No. They were passing a function to createServer that takes two arguments. Those functions will later be called with whatever argument the caller puts in. e.g.:

function caller(otherFunction) {
     otherFunction(2);
 }
caller(function(x) {
    console.log(x);
});

将打印2。

更高级,如果不是你想要的,你可以使用方法属于所有函数,它将创建一个已绑定指定参数的新函数。例如:

More advanced, if this isn't what you want you can use the bind method belong to all functions, which will create a new function with specified arguments already bound. e.g.:

caller(function(x) {
    console.log(x);
}.bind(null, 3);
});

现在打印3,传递给匿名函数的参数2将成为未使用且未命名的参数。

Will now print 3, and the argument 2 passed to the anonymous function will become an unused and unnamed argument.

无论如何,这是一个密集的例子;请查看 bind 的链接文档,以了解绑定如何更好地工作。

Anyway, that is a dense example; please check the linked documentation for bind to understand how binding works better.

这篇关于在JavaScript中传递匿名函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 13:56