I'm still confused when it comes to scope when working with object's methods. In the code below I have two neighbors. Each has it's own method.
var counter = 0;
var neighbor1 = {
name: 'John',
myFunction: function () {
console.log(this.name)
this.doStuff();
}
};
var neighbor2 = {
name: 'Bob',
doOtherStuff: function () {
console.log(this.name);
if(counter>5) {
return false;
} else {
counter++;
this.myFunction();
}
}
};
neighbor1.doStuff = neighbor2.doOtherStuff;
neighbor1.myFunction();
I understand when I call the neighbor1.myFunction method that it will call the neighbor2.doOtherStuff method because I've used the assignment operator above. What I don't understand is why 'this' will always be the neighbor1 object (John) and never the neighbor2 object (Bob). Can someone please explain in simple terms why neighbor1 is always 'this'? Thanks!