如何理解JS领域 [英] How to understand JS realms

查看:119
本文介绍了如何理解JS领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ECMAScript规范中,引入了领域"的概念:

In ECMAScript specification there is notion of "realms" introduced:

在对其进行评估之前,所有ECMAScript代码必须与一个领域相关联.从概念上讲,领域包括 一组内部对象,一个ECMAScript全局环境,所有已加载的ECMAScript代码 在该全球环境以及其他相关状态和资源的范围内.

Before it is evaluated, all ECMAScript code must be associated with a realm. Conceptually, a realm consists of a set of intrinsic objects, an ECMAScript global environment, all of the ECMAScript code that is loaded within the scope of that global environment, and other associated state and resources.

在Rauschmayer的书"Speaking JavaScript"中,作者写到了可以跨越领域的对象:

In Rauschmayer's book "Speaking JavaScript" author writes about objects which can cross realms:

在Web浏览器中,每个框架和窗口都有其自己的领域,并具有单独的全局变量.这就阻止了instanceof对跨领域的对象起作用.

In web browsers, each frame and window has its own realm with separate global variables. That prevents instanceof from working for objects that cross realms.

领域"的确切构成是什么?除了框架之外,还能将网站代码分离到另一个领域的内容是什么?

What exactly constitutes "realm"? What else besides frame can separate websites code to another realm and what are the consequences?

推荐答案

该语言参考使用抽象术语,因为JavaScript环境可能差异很大.在浏览器中,一个窗口(框架,使用window.open()打开的窗口或只是一个普通的浏览器选项卡)就是一个领域.网络工作者是与窗口不同的领域,但这是一个领域.服务人员也是如此.

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.

对象可能跨越领域边界,因为从公共基本窗口打开的窗口可以通过函数调用和简单的变量引用进行互通.您引用的摘录中提到instanceof与此有关.在<iframe>窗口中考虑以下代码:

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
  }
}

行不通.为什么?因为<iframe>窗口中构造的数组是从该领域中的Array构造函数构造的,所以该数组不是是从父窗口中的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.

在Web工作人员领域和窗口领域之间有一个更强大的墙",并且在这些交互中不会发生这种影响.

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

这篇关于如何理解JS领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆