简体   繁体   中英

value of variable not changing after update

I have the following code :

function change(initial) {
  let a = initial;
  console.log(a);
  return [
    a,
    (v) => {
      a = v;
    }
  ];
}

const [val, setter] = change("initial");

console.log(val);
setter("s");
console.log(val);

Val is staying the same eventhough setter has been called. https://codesandbox.io/s/youthful-sun-ewqts?file=/src/index.js:0-212

If i change the return statement to this instead :

  return [
    () => a,
    (v) => {
      a = v;
    }
  ];

and then call val() as a function it works. But i want to understand why this is.

Here is what is happening:

  1. Function is called with initial value "initial"
  2. Initial value is saved as "a"
  3. Array is returned with the current value of "a": "initial"
  4. Setter function is called and the value of "a" is changed inside the function
  5. Array value stays the same because values are not linked

How about something like this:

function change(initial) {
  console.log(initial);
  return {
    get value() {
      return initial;
    },
    set value(v) {
      return initial = v;
    },
    setter: function(v) {
      return initial = v;
    }
  };
}

const obj = change("initial");

const { setter } = obj;

console.log(obj.value);
//initial
setter("s");
console.log(obj.value);
//s
obj.value = "val";
console.log(obj.value);
//val

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