函数getFunc
没有传入参数,为什么这段代码能够工作?
function getFunc() {
const a = 7;
return b => {
console.log(a+b);
} }
const f = getFunc();
f(5); //12
函数getFunc
没有传入参数,为什么这段代码能够工作?
function getFunc() {
const a = 7;
return b => {
console.log(a+b);
} }
const f = getFunc();
f(5); //12
getFunc返回匿名函数
b =>{
console.log(a+b);
}
当你调用getFunc时,实际上你在调用console.log(7+parameter)
这被称为闭包。
在JavaScript中,函数内的代码可以访问该函数内定义的变量以及所有父函数中定义的变量。如果您在子函数中引用了在父函数中定义的变量并返回子函数,则JavaScript将保留来自父函数的变量,并且它们将在返回的函数中可用。
在您的示例中,您正在返回子函数。
b => {
console.log(a+b);
}
从getFunc
函数中获取变量a
,以便子函数仍然可以访问父函数中定义的变量。当您执行f(5)
时,子函数执行7 + 5
表达式,在控制台中得到12
。
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
getFunc
返回的函数确实需要一个参数。 - CertainPerformancegetFunc
返回一个函数。 - vizsatiz