33

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

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.

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

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?

M. Twarog
  • 2,418
  • 3
  • 21
  • 39
  • Is there some particular issue you're facing or are you just trying to understand the concept? – Pointy Apr 14 '18 at 14:14
  • I am trying to understand the concept. I found references to realms in different books about JS, but never any verbose description of this topic. – M. Twarog Apr 14 '18 at 14:18
  • Other than inter-window function calls, which depending on your front-end architecture may or may not be something you have to worry about, the "realm" concept is really not something that comes up as a fundamental concept. A realm is the place where the global standard constructors like `Object` and `Array` "live". – Pointy Apr 14 '18 at 14:20
  • 1
    @Pointy I think it's more important to state that every realm has its own "global" scope :-) – Bergi Apr 14 '18 at 17:03

1 Answers1

43

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.

Rohan Talip
  • 356
  • 4
  • 13
Pointy
  • 405,095
  • 59
  • 585
  • 614