I am fairly new to Javascript and stomped across this while writing some frontend code. I reproduced this here:
var obj1 = {
func1(val) {
if (!this.obj2) {
this.obj2 = {
func2() {
console.log(val);
}
}
}
this.obj2.func2();
}
}
obj1.func1(10);
obj1.func1(20);
Why is the value of the val not getting changed inside the func2() method? It seems that only the value is getting copied to the object obj2 without taking the reference into consideration.
But it works perfectly when I change the code to this:
var obj1 = {
func1(val) {
this.val = val;
var that = this;
if (!this.obj2) {
this.obj2 = {
func2() {
console.log(that.val)
}
}
}
this.obj2.func2();
}
}
obj1.func1(10);
obj1.func1(20);
Can anyone tell the reason behind the difference? Is it something to do with the scope?