0

I know that ,this actually is determined by the callsite where the function actually gets called

var c={
  name:"john",
  func:function()
  {
    console.log(this.name)
  }
}

c.func();  // why it returns john and why not undefined ,as the call site is window 

var c = {
  name: "john",
  func: function() {
    console.log(this.name)
  }
}

c.func();

function data() {
  let name = "hh";
  console.log(this.name)
}

data(); // returns different
gANDALF
  • 360
  • 4
  • 21
  • `this` isn't set by the call site at all. It's set by *how* you call the function and whether it has a bound `this`, or (for arrow functions) where the function is defined. – T.J. Crowder Aug 18 '21 at 10:43
  • The value of `this` is determined at call *time* not at the place in code it was called. The fact that `c.func()` is in the global context is irrelevant, the only relevant information is that you call `func()` on `c`, therefore `this = c`. As a rule of thumb anything *before* the last `.` becomes the value of `this`. If you had `a.b.c.func()` then `this = a.b.c`. If it was `b.c.func()` then `this = b.c` – VLAZ Aug 18 '21 at 10:44

0 Answers0