the function should be like function trueOrFalse()
, it should not keep anything in global scope, everything has to be scoped local to the function. the returned value should be true
or false
and next time it should return the inverse.
You're on the right track. A closure and a local variable is all you need.
function gen () {
let state = false;
return function () {
return state = !state;
}
}
const trueFalse = gen();
trueFalse() //true
trueFalse() //false
Regarding the comment, it's possible to do this without a closure using a property on the function itself.
function trueOrFalse () {
return trueOrFalse.state = !trueOrFalse.state;
}
trueOrFalse() //true
trueOrFalse() //false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.