How to understand JS realms

我是研究僧i 提交于 2019-11-30 18:18:05
Pointy

The language reference uses abstract terms because JavaScript environments can vary widely. In the browser, a window (a frame, a window opened with window.open(), or just a plain browser tab) is a realm. A web worker is a different kind of realm than a window, but it's a realm. Same goes for service workers.

It's possible for an object to cross realm boundaries because windows opened from a common base window can intercommunicate via function calls and simple variable references. The mention of instanceof in that excerpt you quoted has to do with that. Consider this code in an <iframe> window:

window.parent.someFunction(["hello", "world"]);

Then imagine a function in the parent window:

function someFunction(arg) {
  if (arg instanceof Array) {
    // ... operate on the array
  }
}

That won't work. Why? Because the array constructed in the <iframe> window was constructed from the Array constructor in that realm, and therefore the array is not an instance constructed from the Array in the parent window.

There's a much stronger "wall" between web worker realms and window realms, and such effects don't happen in those interactions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!