I have a question concerning object methods and storing them inside other objects.How come obj[1]()
still executes the old method, although it is overwritten by fn.getN1 = "test"
? I would think I can't execute it anymore. And it doesnt exist when I console .log fn
, but is it still stored somewhere in memory?
Also, would be great if you can tell me if this is a bad practice or not. I'm not quite knowledgable this.
function Factory() {
let n = 0;
function getN1() {
console.log(n);
}
function getN2() {
console.log(n);
}
function incrN() {
n++
}
return {getN1, getN2, incrN}
}
let fn = Factory();
let obj = {1: fn.getN1, 2: fn.incrN}
fn.getN1 = "test";
console.log(fn);
obj["2"]();
obj[1]();
fn.getN2();
console.log(fn.getN1);