Consider a simple factory which self-updates -
function MyFactory(){
var _data = []; // initial value
function onLoad(response){
// assign the incoming value to our '_data' variable
_data = response;
}
// some sort of ajax to get the data
function getData() {
// ajax.fecth('/url', onLoad);
// pseudo-ajax
onLoad([4,5,6]);
}
// public methods / properties
this.getData = getData;
this.data = _data;
}
(Can you see the problem here? Worth taking a second.) I'll spell it out -
// create the object
var factory = new MyFactory();
// get the data
console.log(factory.data); // [] ok
// get new data [1,2,3], and assign to the data property
factory.getData();
// what have we now got?
console.log(factory.data); // [] argh, expected [1,2,3]
This is not what we want at all. this.data should return the new array... but doesn't. It continues to reference the original array, even though we've internally updated our object.
There is a solution - instead of replacing the value of data, we can do this -
function onLoad(response){
// take care to reuse the object
_data.length = 0;
Array.prototype.push.apply(_data, response);
}
... which is okay, but feels a bit of a hack.
My question is - what would be a better pattern of MyFactory which would ensure that we can update its data property so that it always returns the expected value.
factory.datais different from the variabledatawithin themyFactoryfunction.factory.dataisthis.datainside themyFactoryfunction,