简体   繁体   中英

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

I tried to implement a small connect function. It should take an object in parameter and put them into an function. My expectation the latest object should be used always. Looks like it's not true.

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

The variable in execute is an argument, ie a local variable. It doesn't refer to the global store variable.

Either remove the argument and refer to the global variable directly, or change properties of the object instead, eg store.type = "updated"; .

What is the point of this bizarre arrangement of functions anyways?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM