Please do not mark as duplicate before reading it. I have a good understanding of the topic and I even wrote an article about it!
And yet, the code below baffles me and I think its not the question you think it is ;-)
I have the following code.
function Test(name) {
this.name = name;
this.f1();
}
Test.prototype.f1 = function() {
console.log('[Function f1] Is Test = ' + (this instanceof Test) + ', name = "' + this.name + '"');
var f = this['f2'];
f();
// f2(); works!
// this['f2'](); works as well!
};
Test.prototype.f2 = function() {
console.log('[Function f2] Is Test = ' + (this instanceof Test) + ', name = "' + this.name + '"');
};
var t = new Test('Mike');
Running the code produces
[Function f1] Is Test = true, name = "Mike"
[Function f2] Is Test = false, name = "undefined"
So when calling the function is that (admittedly) strange way loses the scope for this
.
I can always do f.apply(this)
which will work but I am really trying to understand what is happening here.
Any clues?