Primary objective: Allow arr information retrieval exclusively through the getArray method.
Secondary objective: Enable arr data modification solely through the addToArray method.
function TestObj(){
var arr = [];
var b = 3;
this.getArray = function(){
return arr;
};
this.addToArray = function(val){
arr.push(val);
};
this.getNumber = function(){
return b;
}
this.setNumber = function(val){
b = val;
}
}
var obj = new TestObj();
obj.addToArray('derp');
console.log(obj.getArray());
//['derp']
obj.getArray().push('aderp');
console.log(obj.getArray().length);
// 2
There is some confusion. Isn't getArray supposed to return a reference to the arr array, not the array itself? This concept extends from closures, am I missing something here?
Reflective process:
Considering,
obj.getNumber()
yields 3,
and
obj.setNumber(4)
followed by
obj.getNumber()
results in 4
trying:
obj.getNumber() = 5
fails with "invalid left-hand..."
in that case, why does
obj.getArray().push('thing')
have the ability to modify the array...since it is a variable within the function's scope... it should be encapsulated within the closure, accessible only through the getArray / addToArray interface...