// Example 0, revisited - this is BUGGY!
function useState(initialValue) {
var _val = initialValue
// no state() function
function setState(newVal) {
_val = newVal
}
return [_val, setState] // directly exposing _val
}
var [foo, setFoo] = useState({x: 1})
console.log(foo) // {x: 1}
setFoo({x: 2}) // sets _val inside useState's scope
console.log(foo) // {x: 1}
I understand a pass-by-value or pass-by-reference problem. But below example still confused me? Can you tell me which step I am wrong. That is: We pass by an object to _val
, but it's not change the reference value outside.
Is this means the _val
in closure is different from outside? Although they looks same. So when we assign an object to it, it refer to a new memory, and this memory is shared by all closures in one function. Because another example below is correct.
function useState(initialValue) {
var _val = initialValue
// no state() function
function setState(newVal) {
_val = newVal
}
function getState() {
return _val
}
return [getState, setState]
}
var [getState, setFoo] = useState({x: 1})
console.log(getState()) // {x: 1}
setFoo({x: 2})
console.log(getState()) // {x: 2}