Search code examples
javascriptfetch-apifunction-binding

Why does bind fix "failed to execute 'fetch' on 'Window' illegal invocation" error?


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?


Solution

  • 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.