Relationship between globals, Realms, and global environment records
Boris Zbarsky
bzbarsky at mit.edu
Tue Nov 25 09:20:02 PST 2014
On 11/25/14, 12:01 PM, Domenic Denicola wrote:
> However, interestingly:
>
> ```js
> onload = function () {
> var oldSelf = self;
> self.x = "test";
> console.log(self.x); // "test" of course
> console.log(x); // "test"
> document.open("text/html");
> console.log(self.x); // undefined
> console.log(x); // "test" still
> console.log(self === oldSelf); // true
> };
> ```
>
> So, if I'm using my terms correctly, the "global environment record" contains the same variables, even though the global object has a completely new set of properties?
You just said "the global object".
There are two different global objects here, per spec. Let's call them
X and Y (I considered B for "before" and A for "after", but that would
be a bit confusing).
We start out with global X (a Window instance). The function statement
is evaluated with global X, so the function that's created has the Realm
of X as its Realm. This function is then assigned to the onload
property of X.
The load event fires, and we call the function. It calls the "self"
getter, which returns a WindowProxy. This is a proxy which is currently
pointing to X. When we do self.x = "test", the set is forwarded along
to X. When you do console.log(self.x) the get is forwarded along to X.
When you do console.log(x), the "x" property is obviously found on X,
since that's the global of the function.
Alright, now you do document.open(). This creates a new global Y and
changes the WindowProxy we have stored in oldSelf to point to Y instead
of X. Getting "self" from Y returns the same WindowProxy as it used to
return, so self === oldSelf.
Now console.log(self.x) forwards the get to Y, which has no such
property. console.log(x) is still looking up the property "x" on X,
since the function we're in comes from that global, so it gets the value
"test".
Everything here seems sane to me so far. Well, as sane as anything ever
is when WindowProxy is involved.
-Boris
More information about the es-discuss
mailing list