我正在 nodeschool-homepage 上编写函数式编程教程。 。 我是 JS 新手(来自 Java),所以我不了解 JS 的某些方面,例如:
function say(word) {
return function(anotherWord) {
console.log(anotherWord);
}
}
如果我打电话:
say("hi"); // it returns nothing
say("hi", "hi"); // it returns nothing
var said = say("hi"); // asignment
said("hi"); // returns hi -- but why?
said(); // returns undefined;
有人可以向我解释一下外部函数中的“hi”是如何传递到内部函数中的吗?
最佳答案
said("hi"); // returns hi -- but why?
因为内部函数定义为
function(anotherWord) {
console.log(anotherWord);
}
这意味着它记录它传递的第一个参数。您正在传递 'hi'
,因此它会记录 'hi'
。
how t.. f... the "hi" in the outer function is passed in the inner function?
事实并非如此。内部函数仅访问其自己的参数。将什么作为参数传递给第一个函数并不重要。 say()('hi')
、say('foo')('hi')
都是等价的。重要的是传递给第二个函数的参数。
如果您将函数定义为
function say(word) {
return function(anotherWord) {
console.log(word, anotherWord);
}
}
现在内部函数还访问外部函数的第一个参数,因此您会得到不同的结果。
为什么这有效?因为JS中所有函数都是closures因此他们可以访问更高范围的变量绑定(bind)。
关于返回带有参数的函数的 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27535428/