簡體   English   中英

函數參數的javascript閉包在更新時不會反映出來

[英]javascript closure from function's parameter is not reflected when it is updated

我試圖實現一個小連接功能。 它應該在參數中取一個對象並將它們放入一個函數中。 我的期望應該始終使用最新的對象。 看起來這不是真的。

let store = { type: 'initial' };

console.log(store);

function connect(param) {
  const connected2 = function (fn) {

    return function () {
      return fn(param);
    }
  };
  return connected2;
}

function execute(store) {
  console.log(store);
}

const connected = connect(store)(execute);

connected(); // console => { type: 'initial' }
store = {type: 'updated'};
connected(); // console { type: 'initial' } but expect updated

execute的變量是一個參數,即一個局部變量。 它不引用全局store變量。

刪除參數並直接引用全局變量,或改為改變對象的屬性,例如store.type = "updated";

這種離奇的功能安排有什么意義呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM