0

When trying to execute the following snippet, I expected the doFoo.call(obj, obj.foo) call to return "inside obj" as the dynamic scope of the previous element in the call stack has a reference to a but the call has the global context instead. What am I missing here?

function foo() {
  // debugger
  console.log(this, this.a);
}

function doFoo(fn) {
  // `fn` is just another reference to `foo`
  // debugger 
  fn()
  // <-- call-site!
}

var obj = {
  a: 'inside obj',
  foo: foo
};

var a = "oops, global"; // `a` also property on global object

doFoo(obj.foo); // "oops, global"
doFoo.call(obj, obj.foo) // "oops, global"```
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
PsNeo7
  • 1
  • `this` is not dynamically scoped. Every call has its own `this` context. – Barmar Feb 18 '22 at 18:56
  • `call` overrides the value of `this` **for the function** it calls. So you override it for `doFoo` (which doesn't use `this`) which then calls `fn()` in the context of `window`. – Quentin Feb 18 '22 at 18:58
  • It's *how* you call something which determines the value of `this`, not what the value of `this` was at the call site. Calling a `fn()` will ***always*** mean that `this = undefined`. Which in loose mode is substituted with the global object. – VLAZ Feb 18 '22 at 18:59
  • @Quentin @VLAZ so is the default scope(in loose mode) in all calls with ```this = undefined``` the global object? @Barmar it seems like even though it might not be purely dynamic, it does seem to borrow a lot of it's behaviour for it? – PsNeo7 Feb 18 '22 at 19:28
  • "*so is the default scope(in loose mode) in all calls with this = undefined the global object?*" yes. In strict mode `this = undefined` stays `undefined`. In loose mode it's `window` instead (in browsers). "*it seems like even though it might not be purely dynamic, it does seem to borrow a lot of it's behaviour for it?*" sort of. You could treat `this` as dynamic scope to an extent if you use `this.foo` in a function and call it with a different `this`. On the other hand, `this` acts a lot more like a "hidden" argument to the function. – VLAZ Feb 18 '22 at 19:57

0 Answers0