0

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?

Mike M
  • 4,447
  • 2
  • 33
  • 49
  • 2
    because value of `this` will change depend on how you are invoking the function – Arun P Johny Feb 22 '16 at 08:47
  • I understand that, and I though I had a good understanding about it until I tried the code above. Can you please be more specific. – Mike M Feb 22 '16 at 08:57
  • In your article, you state _"Now, in most cases* the this keyword will point to the object that the function is a member of. So this, inside of Test, will point to root because Test is implicitly attached to root!"_ This however is not true. As described in both the dupes linked to, `this` is not set to the object on which the function is created/defined/located, but instead depends entirely on how the function is invoked. – James Thorpe Feb 22 '16 at 09:18

0 Answers0