2

I'm just curious,

This...

let s = { f: window.fetch };
s.f("https://www.google.com");

fails with

Failed to execute 'fetch' on 'Window': Illegal invocation

While this works...

let s = { f: window.fetch.bind(window) }; 
s.f("https://www.google.com");

How does the latter fix the issue? Is there any theory behind why it works that way?

Phil
  • 157,677
  • 23
  • 242
  • 245
jeffbRTC
  • 1,941
  • 10
  • 29

1 Answers1

2

For some internal purpose, the fetch function must have this be the same as window. When you create your own object and just assign the fetch function as one of its properties, the fetch function has no access to the window object as this.

The fetch specification describes things the window might be used for. You might be able to make your original code work by setting no-window, but I have not tested that.

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
  • Is this documented on ECMA Spec? – jeffbRTC Nov 07 '21 at 22:32
  • @jeffbRTC `fetch()` is not part of ES. [It's a web spec](https://fetch.spec.whatwg.org/) – VLAZ Nov 07 '21 at 22:33
  • @VLAZ My apologies, where can I find it on the web spec you linked? – jeffbRTC Nov 07 '21 at 22:35
  • @jeffbRTC the entire spec is only about `fetch()`. I'm not sure where in it it would say that requires `window` (or if it even does). – VLAZ Nov 07 '21 at 22:36
  • @VLAZ Okay, I was looking what's this vague internal purpose mentioned on the answer .. – jeffbRTC Nov 07 '21 at 22:37
  • 1
    @jeffbRTC "internal" might be implementation dependent. But I'm not making a claim that's the case. I've not gone through the spec to confirm or deny this. – VLAZ Nov 07 '21 at 22:38
  • @VLAZ I tested on Firefox - `'fetch' called on an object that does not implement interface Window` – jeffbRTC Nov 07 '21 at 22:41