下面的函数从哪里获取参数?

4

函数getFunc没有传入参数,为什么这段代码能够工作?

function getFunc() {
    const a = 7;

    return b => {
        console.log(a+b);
    } }

const f = getFunc();

f(5); //12

12
从调用 getFunc 返回的函数确实需要一个参数。 - CertainPerformance
1
你正在从 getFunc 返回一个函数。 - vizsatiz
1
请参考以下网址:https://eloquentjavascript.net/ - user2864740
1
仅仅传递一本书的链接并不是很有帮助。关于闭包的部分在第五章中有讲解。https://eloquentjavascript.net/05_higher_order.html - oligofren
3个回答

2

getFunc返回匿名函数

b =>{
  console.log(a+b);
}

当你调用getFunc时,实际上你在调用console.log(7+parameter)


我了解你的意思,但是你写的不正确。当调用getFunc时,console.log永远不会被调用。 - oligofren
非常感谢,我现在明白了。加上闭包 const f = function (b) {console.log(a+b)} - Oleg Zinchenko

2

这被称为闭包。

在JavaScript中,函数内的代码可以访问该函数内定义的变量以及所有父函数中定义的变量。如果您在子函数中引用了在父函数中定义的变量并返回子函数,则JavaScript将保留来自父函数的变量,并且它们将在返回的函数中可用。

在您的示例中,您正在返回子函数。

b => {
    console.log(a+b);
}

getFunc函数中获取变量a,以便子函数仍然可以访问父函数中定义的变量。当您执行f(5)时,子函数执行7 + 5表达式,在控制台中得到12


非常感谢,我现在明白了。 - Oleg Zinchenko

1
function getFunc() {
const a = 7;

return function(b) { //it is more clear syntax
    console.log(a+b);
} }

const f = getFunc(); // here we have a function wich get 'b' parameter

f(5); //here we call this function and pass 5 as a 'b' parameter

非常感谢,我现在明白了。 - Oleg Zinchenko
很高兴能够帮助你。请标记我的回答为“答案”,这样其他用户也可以找到这个答案。 - Dmytro Huz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接