0

I passed the function as an argument but this is not bar object neither foo object

  let foo = {
      fooInerFunction(arg) {
          arg();
      }
  }
let bar = {
      barInerFunction() {
          foo.fooInerFunction(function() {
              console.log(this);
          })
      }
  }
bar.barInerFunction()
sina
  • 98
  • 6
  • this is scope of the parent function. like this area: function() { console.log(this); } – Jayesh Naghera Jun 27 '21 at 16:56
  • 1
    @JayeshNaghera that is incorrect, `this` depends on how the function is called. So it is not related to the creation time context of the function. – VLAZ Jun 27 '21 at 16:57
  • 1
    @VLAZ yes but this case it will be like that try with run in console :- let foo = { fooThis: "fooThis", fooInerFunction(arg) { this.fooName = "fooName"; arg(); } } let bar = { barThis: "barThis", barInerFunction() { foo.fooInerFunction(function() { this.fooArg = "fooArg"; console.log(this.fooThis); console.log(this.fooName); console.log(this.barThis); console.log(this.fooArg); }) } } bar.barInerFunction() – Jayesh Naghera Jun 27 '21 at 17:05
  • 1
    @JayeshNaghera the important thing is how the callback is run. That's `arg()`. Since there is no implicit or explicit `this` set with the call (e.g., implicitly `someObj.arg()` will set `this = someObj` while explicitily `arg,call(foo)` will set `this = foo`) then the value of `this` is `undefined`. In non-strict mode `this = undefined` is then converted to `this = window`. You can already you can already see in this in snippet in the OP. There is no "outer function" here at play. Check the two linked duplicates. – VLAZ Jun 27 '21 at 17:35
  • 1
    @JayeshNaghera your example just shows the same behaviour again - `this.fooArg = "fooArg"` will set a property on `window` called `fooArg`. Check after running the code with `console.log(window.fooArg)`. Again, because `this` in the callback will be set to `window` based on how it is called, ***not*** based on how it is created. https://jsbin.com/kadequqeke/1/edit?js,console – VLAZ Jun 27 '21 at 17:38

1 Answers1

1

this keyword generally refers to object on which function is called.

Examples:

a = {"x": 0}
b = {"x": 8}

function logMeX() {
  console.log(this.x)
}

a.logMeX = logMeX;
b.logMeX = logMeX;

a.logMeX() // logs 0
b.logMeX() // logs 8
logMeX() // logs undefined
x = 5; // this is same as doing window.x = 5
logMeX() // logs 5, because if no object is it called on, this is window
Kryštof Vosyka
  • 566
  • 3
  • 15