为什么绑定会修复 "failed to execute 'fetch' on 'Window' illegal invocation" 错误?

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

我只是好奇,

这个...

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

失败

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

虽然这有效...

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

后者如何解决这个问题?为什么它会这样工作,背后有什么理论吗?

出于某些内部目的,fetch 函数必须 thiswindow 相同。当您创建自己的对象并将获取函数分配为其属性之一时,获取函数无法访问 window 对象,如 this.

fetch specification 描述了 window 可能用于的事情。您可能可以通过设置 no-window 让您的原始代码工作,但我还没有测试过。