我不知道代码:const countFrom = x => () => (x++, x);
中的here,作品:
const countFrom = x => () => (x++, x);
let a = countFrom(1)
console.log('output:', a()) // output: 2
console.log('output:', a()) // output: 3
console.log('output:', a()) // output: 4
console.log('output:', a()) // output: 5
.as-console-wrapper {min-height: 100%!important; top: 0;}
x
是外部(x =>
)函数内部的变量,因此所有内部函数(() => (x++, x)
)共享同一变量。每当内部函数执行时,x++
帖子都会递增该变量。逗号运算符(..., x
)计算得出最后一个逗号分隔的表达式,在这种情况下为x
。
如果没有逗号运算符,可能更容易理解:
const counter = x => () => x = x + 1;
//const countFrom = x => () => (x++, x);
//Lets refactor the code a bit:
function countFrom(x){
return function(){
x++;
return x;
}
}
let a = countFrom(1)
//now a is the returned function at line 5, and x is stored as a local variable.
console.log('output:', a()) // output: 2 you call the function at line 5 so it adds 1 to x and returns it
.as-console-wrapper {min-height: 100%!important; top: 0;}
如果您了解某些方面,这很简单:
()=> (x++,x)
(请参阅closure
是什么]return x
,即=> (x)
与=> return x
相同