为什么布尔对象属性不会更新?



我有一个对象数组。每个对象都有一个方法,应该更新名为"find"的同一对象中的布尔属性。

当我调用函数时,属性不会更新。我不知道为什么。

我以为"已找到"的属性可以访问,但事实并非如此??

我在这里创建了一个问题的最小版本:https://codepen.io/sspboyd/pen/XWYKMrv?editors=0011

const gen_s = function () { // generate and return the object
let found = false;
const change_found = function () {
found = true;
};
const update = function () {
change_found();
};
return {
change_found,
found,
update
};
};
const s_arr = []; // initialize an array
s_arr.push(gen_s()); // add a new s object to the array
console.log(s_arr[0].found); // returns 'false'
s_arr.forEach((s) => {
s.update();
});
console.log(s_arr[0].found);

change_found函数更改found的值时,它将更改let found变量指向的值,但gen_s函数返回的对象仍然指向旧值。

你可以使用"holder"模式来修复你的代码,比如:

const gen_s = function () { // generate and return the object
let foundHolder = {value: false};
const change_found = function () {
foundHolder.value = true;
};
const update = function () {
change_found();
};
return {
change_found,
foundHolder,
update
};
};
const s_arr = []; // initialize an array
s_arr.push(gen_s()); // add a new s object to the array
console.log(s_arr[0].foundHolder.value); // returns 'false'
s_arr.forEach((s) => {
s.update();
});
console.log(s_arr[0].foundHolder.value);

或者更好的是,使用一个类:

class S {
constructor() { this.found = false; }
change_found() { this.found = true; }
update() { this.change_found(); }
}
const s_arr = [];
s_arr.push(new S());
console.log(s_arr[0].found);
s_arr.forEach(s => s.update());
console.log(s_arr[0].found);

最新更新