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:
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.