以下函数从何处获取参数?

时间:2018-09-12 08:07:02

标签: javascript function

函数getFunc没有传递参数,为什么此代码有效?

function getFunc() {
    const a = 7;

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

const f = getFunc();

f(5); //12

3 个答案:

答案 0 :(得分:2)

getFunc返回匿名函数

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

因此,当您调用getFunc时,您实际上是在呼叫console.log(7+parameter)

答案 1 :(得分:2)

这叫做闭包。

在JavaScript中,函数内部的代码可以访问此函数内部定义的变量以及所有父函数中定义的变量。 如果您在父函数中定义的子函数中引用了变量,然后返回了子函数,则JavaScript将保留父函数中的变量,并且这些变量将在返回的函数中可用。

在您的示例中,您将返回子功能

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

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

答案 2 :(得分: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