My goal is to create one new job object at a time with an active state of true, and then set the last created job objects' active state to false.
I'm attempting to do this using Object.assign() in an object factory (apologies if this isn't exactly the right terminology).
The problem I'm having is that the state.active property is updated and correct in the gen_job() function, BUT incorrect when read inside the update_all_jobs() function.
I'd like to do this without classes or using the 'this' keyword as an exercise to improve my understanding of the language.
Many thanks if anyone can shed some light on what I'm doing wrong here.
Minimal example, also on Codepen.io:
let job_counter = 0; // helps with debugging
let jobs = []; // an array to store job objects
// Return an object with an 'active' property set to true
const create_job = (x, y) => {
// define some state properties for the job object
let state = {
active: true,
ox: x,
oy: y,
job_id: job_counter++,
};
return Object.assign({}, state, updater(state));
};
const updater = function (state) {
return {
update: function () {
console.log(
`Inside update_all_jobs(). Job_id: ${state.job_id}, state.active is ${state.active}`
);
}
};
};
const gen_job = () => {
// test to see if there is a previously created job object, and if true,
// set the last created object's active state to false
if (jobs.length > 0) {
jobs[jobs.length - 1].active = false;
}
jobs.push(create_job(10, 20));
jobs.forEach((jb) =>
console.log(
// works here!?
`Inside gen_job(): Job_id: ${jb.job_id}, active state: ${jb.active}`
)
);
};
// This is called after a new job is created.
const update_all_jobs = function () {
jobs.forEach((jb) => {
jb.update();
});
};
gen_job();
update_all_jobs();
gen_job();
update_all_jobs();
// Console output //
/*
"Inside gen_job(): Job_id: 0, active state: true"
"Inside update_all_jobs(). Job_id: 0, state.active is true"
"Inside gen_job(): Job_id: 0, active state: false"
"Inside gen_job(): Job_id: 1, active state: true"
"Inside update_all_jobs(). Job_id: 0, state.active is true"
"Inside update_all_jobs(). Job_id: 1, state.active is true"
*/
// Why does Job_id 0 switch from false to true??