0

I have a problem understanding JavaScript context in the below snippet.

Why is the context different?

var subscribers = [];

subscribers.push(function () {
    return this;
});
const subscriber = subscribers[0];
subscriber() === window // true
subscribers[0]() === subscribers // true

Please NOTE that an not asking how this works, as described in https://stackoverflow.com/a/3127440/3563013, but am asking why the difference in the value of this for the same subscriber.

McKabue
  • 2,076
  • 1
  • 19
  • 34
  • Its not a duplicate. – McKabue Sep 16 '19 at 14:45
  • Have you checked? It goes quite in depth in how the `this` context is used and initialised. – VLAZ Sep 16 '19 at 14:46
  • 2
    @McKabue in the accepted answer, the section labeled "Initial global execution context" talks about your `subscriber()` case, and the section labeled "Entering function code" discusses your `subscribers[0]()` case. `If a function is called on an object, such as in obj.myMethod() or the equivalent obj["myMethod"](), then ThisBinding is set to the object` – Nicholas Tower Sep 16 '19 at 14:48
  • what about `const subscriber = subscribers[0]; subscriber() === window // true` ? The answer has not written about it... – McKabue Sep 16 '19 at 14:55
  • please unmark this question as duplicate because its not... what am asking is not answered in the referenced question! – McKabue Sep 16 '19 at 14:56
  • @VLAZ Can you please answer how my question is a duplicate when there is no mention or explanation for my case? or is it just fun to mark questions as duplicate? – McKabue Sep 16 '19 at 15:08
  • @McKabue as you were pointed before, the **Entering function code** section directly answers it right at the start: "*This occurs when calling a function. If a function is called on an object, such as in obj.myMethod() or the equivalent obj["myMethod"](), then ThisBinding is set to the object (obj in the example; §13.2.1). In most other cases, ThisBinding is set to the global object (§10.4.3).*" with `subscribers[0]() === subscribers` the `this` binding is initialised as `subscriber` - same as with `obj["myMethod"]()`. – VLAZ Sep 16 '19 at 15:13
  • In the case of `subscriber()` you are not calling it on an object, so you get the global object - `window` but only in non-strict mode. – VLAZ Sep 16 '19 at 15:13
  • @McKabue Let me answer your question in the comments. The square bracket notation is nothing more than a dynamic way to access object properties. Assume the following: `obj = { a: function() { return this; } }` now `obj.a() === obj //=> true` could also be written as `obj["a"]() === obj //=> true`. The same applies for arrays, with the difference that you can't use `arr.0()` because `0` is not a valid identifier. – 3limin4t0r Sep 16 '19 at 15:15

0 Answers0