Consider this example:
function Dummy(buddy) {
this._buddy = buddy;
}
Dummy.prototype.greetBuddy = function() {
console.log('Hello, '+this._buddy);
}
function outerGreet1(dummy) {
var func = dummy.greetBuddy;
func();
}
function outerGreet2(dummy) {
dummy.greetBuddy();
}
Suffice to say this fails to convey why I'm doing this, but is a basic distillation of what I'm encountering. I just fixed a bug in my program that was resulting from this distinction. outerGreet1 will throw an error because it cannot find this._buddy, while outerGreet2 will print the expected result.
I was only copying the function to a local variable for code clarity, but obviously this is a ripe learning experience for me. What exactly is going on here? I'm guessing 'this' ends up referring to the outerGreet1 function? I am coming from Java so I understand that JavaScript only has function scope, but why does creating a new reference to the function change its behavior? I was under the impression that 'this' corresponded to the current scope, and I'm not sure how the reassignment alters scope, so my understanding is flawed somewhere.
Apologies if this is a common JavaScript question but I had great difficulty phrasing my search in a way that turned up any answers.