简体   繁体   English

函数参数的javascript闭包在更新时不会反映出来

[英]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. execute的变量是一个参数,即一个局部变量。 It doesn't refer to the global store variable. 它不引用全局store变量。

Either remove the argument and refer to the global variable directly, or change properties of the object instead, eg store.type = "updated"; 删除参数并直接引用全局变量,或改为改变对象的属性,例如store.type = "updated"; .

What is the point of this bizarre arrangement of functions anyways? 这种离奇的功能安排有什么意义呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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