在这种特殊情况下 Javascript 会发生什么(通过共享调用)?

What happens in Javascript in this particular case (Call by sharing)?

Javascript 使用共享调用,但我有一些与 React 相关的问题。

在函数中设置状态(setState Hook 或 Class State)会发生什么?例如:

const [myState, setMyState] = useState(null);

const foo = () => {
   const bar = {'prop': 1};
   setMyState(bar);
}

foo();

javascript 如何跟踪函数内部设置的状态值,据我所知,bar 在执行 foo 后死亡。

setState 是复制传递的值还是我遗漏了什么?

价值观不会消亡。值永远存在于内存中,只要没有人过来将它们擦除(垃圾收集器)。但是,只要您在内存中引用了该值,垃圾收集器就不会触及它。现在 bar 包含对您案例中对象的引用。当您调用 setMyState 时,您传递了引用,因此只要引用存在,setMyState 就可以访问内存中的对象。最终 React 将该引用存储在某个地方,return 它在重新渲染时 myState

  // A very simplified version of useState:
 let state; // the secret place were we keep the reference

 function useState(initial) {
  if(!state) state = initial;
  function setState(value) { // here we get the reference
    // food for thought: what happens to the object state referenced before here?
    state = value; // and here we store it
    render();
  }
  return [state, setState]; // here we pass on the reference to the render function
 }

 function render() {
  const [counter, setCounter] = useState({ value: 1 }); // here we get a reference to the object
  console.log(counter);
  setTimeout(() => setCounter({ value: counter.value + 1 }), 1000); // and here we pass a new one in
 }

 render();

如果你不传递引用,那么当foo的执行结束时,没有人可以访问bar,因此也没有人可以访问位于内存中的对象,因此垃圾收集器最终会出现。


以上都是骗人的。 JavaScript 中没有引用这样的东西(好吧,有一个 Reference ,但它在做别的事情),也没有内存这样的东西。根据规范,这些值恰好在 "somewhere" 左右。现在在实践中引擎确实将值存储在内存中,因此我所说的一切或多或少对所有主要引擎都是正确的