有时我会看到 JavaScript 是用一个提供的参数编写的,该参数已经有一个设定值或者是一个带有方法的对象。以这个 jQuery 示例为例:
$(".selector").children().each(function(i) {
console.log(i);
});
登录时
i
, 你会得到任何 i
的值在查看 jQuery each
中的选择器子项时处于该迭代中方法。以这个 Node.js 为例:
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
你可以在这里看到
request
和 response
正在被传递,并且它们包含自己的可以操作的方法。对我来说,这看起来像是将函数传递给
createServer
具有两个已附加方法的参数的函数。我的问题是多部分的:
最佳答案
To me, this looks like were passing a function to the createServer function with two arguments that have methods already attached to them.
不,他们将函数传递给
createServer
这需要两个参数。稍后将使用调用者输入的任何参数调用这些函数。例如:function caller(otherFunction) {
otherFunction(2);
}
caller(function(x) {
console.log(x);
});
将打印 2。
更高级,如果这不是您想要的,您可以使用 bind方法属于所有函数,它将创建一个已绑定(bind)指定参数的新函数。例如。:
caller(function(x) {
console.log(x);
}.bind(null, 3);
});
现在将打印 3,传递给匿名函数的参数 2 将成为未使用且未命名的参数。
无论如何,这是一个密集的例子;请查看
bind
的链接文档了解绑定(bind)如何更好地工作。
关于javascript - 在 JavaScript 中的匿名函数中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195750/