gpt4 book ai didi

javascript - 如何理解 JS 领域

转载 作者:可可西里 更新时间:2023-11-01 02:23:32 28 4
gpt4 key购买 nike

在 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 web browsers, each frame and window has its own realm with separate global variables. That prevents instanceof from working for objects that cross realms.

究竟什么是“境界”?除了框架还有什么可以将网站代码分隔到另一个领域,其后果是什么?

最佳答案

语言引用使用抽象术语,因为 JavaScript 环境可能千差万别。在浏览器中,一个窗口(一个框架,一个用 window.open() 打开的窗口,或者只是一个普通的浏览器选项卡)是一个领域。 Web Worker 是一种不同于窗口的领域,但它是一个领域。服务人员也是如此。

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

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

然后在父窗口中想象一个函数:

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

行不通。为什么?因为数组构造在<iframe> window 是从该领域中的 Array 构造函数构造的,因此该数组不是从父窗口中的 Array 构造的实例。

web worker 领域和窗口领域之间有一堵更坚固的“墙”,在这些交互中不会发生这种影响。

关于javascript - 如何理解 JS 领域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49832187/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com