0
// 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}
CodeAlien
  • 766
  • 2
  • 7
  • 15
  • 1
    "It's not a pass-by-value or pass-by-reference problem." — It really is – Quentin Sep 24 '22 at 08:22
  • 1
    "Below example we pass by a reference." — No, you don't. You can't have a reference to a variable. – Quentin Sep 24 '22 at 08:22
  • "*Does this mean all the closures in same function share the same memory?*" - [yes](https://stackoverflow.com/q/111102/1048572) – Bergi Sep 24 '22 at 14:18
  • @Bergi As the closure memory model, I thought the outside and closures share the same reference `_val`, but it's not? So the closures create another reference? just have the same name? – CodeAlien Sep 25 '22 at 00:23
  • What do you mean by "outside"? Notice that `_val` is not a reference, it's a variable - which is referred to by all closures that have it in their scope – Bergi Sep 25 '22 at 00:32
  • `Outside` means function the closure belongs. `_val` is used by function and closures inside, why we assign an object, we cannot change it? @Bergi – CodeAlien Sep 25 '22 at 00:49
  • 2
    This has nothing to do with objects. Variables (and closures over them) work the same regardless whether they hold an object or a primitive value. "Changing an object" means mutating its properties, e.g. `_val.x = 2` or `foo.x = 2`, but that's not what you are doing. `foo` and `_val` are completely separate variables, even if they currently hold the same value, it doesn't mean that setting one variable to a different value affects the other. – Bergi Sep 25 '22 at 02:06
  • Thanks @Bergi, you are exactly right. – CodeAlien Sep 25 '22 at 02:33

0 Answers0