0

I'm learning about "this" in JS and I have the following code:

var person1 = {
  firstName: "John",
  lastName: "Snow",

  printName: function(){
    console.log(this);
  }
}

var person2 = {
  firstName: "Aria",
  lastName: "Stark",

  printName: function(callbackFunction){
    console.log(this);
    callbackFunction();
  }
}

person1.printName();
person2.printName(person1.printName);

The output of this code is:

person1

person2

window

I understand why to context is person1 and person2 accordingly but why when I call the callback the context is window and not person2?

RiskX
  • 561
  • 6
  • 20
  • Because the value of `this` is determined by how the function is called.. `callbackFunction` is called without any context hence global(`window`) is returned... – Rayon Jul 09 '16 at 08:25
  • Hi Rayon, What I don't understand is why no context? I called "printName" when person 2 was the context so why when I call the callbackFunction from within "printName" the context doesn't remain person2? – RiskX Jul 09 '16 at 08:46
  • As I commented on answer – _"It matters how they are called, not how they are passed..."_ Refer ___[`this`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this)___ – Rayon Jul 09 '16 at 08:48
  • So is it right to say that when calling the callBackFunction the browser looks for it in the current context(person2 in this case) and after it doesn't find that function it looks for it higher in the hierarchy(window in this case)? – RiskX Jul 09 '16 at 09:03

1 Answers1

0

callbackFunction in your case is an expression (of type function) which is taking the context based on how they are invoked (window's context if no context is provided).

If you want the person1's method to be called then tweak it as

var person1 = {
  firstName: "John",
  lastName: "Snow",

  printName: function(){
    console.log(this);
  }
}

var person2 = {
  firstName: "Aria",
  lastName: "Stark",

  printName: function(context, callbackFunction){
    console.log(this);
    callbackFunction.bind(context).call(null);
  }
}

person1.printName();
person2.printName(person1,person1.printName);

Here I am passing the context also, in which the callbackFunction should be invoked.

And in the function person2.printName I am binding the context to the callback funciton.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Guru – _"taking the context of from where it is being passed"_ sounds wrong.. It matters how they are called, not how they are passed... – Rayon Jul 09 '16 at 08:27
  • http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback seems perfect dupe to me.. Will flag if you agree... – Rayon Jul 09 '16 at 08:28
  • 1
    @Rayon You are right about both comments – gurvinder372 Jul 09 '16 at 08:29