4.4 In browsers, globalThis does not point directly to the global object
In browsers, globalThis
does not point directly to the global, there is an indirection. As an example, consider an iframe on a web page:
- Whenever the
src
of the iframe changes, it gets a new global object. - However,
globalThis
always has the same value. That value can be checked from outside the iframe, as demonstrated below (inspired by an example in theglobalThis
proposal).
File parent.html
:
<iframe src="iframe.html?first"></iframe>
<script>
const iframe = document.querySelector('iframe');
const icw = iframe.contentWindow; // `globalThis` of iframe
iframe.onload = () => {
// Access properties of global object of iframe
const firstGlobalThis = icw.globalThis;
const firstArray = icw.Array;
console.log(icw.iframeName); // 'first'
iframe.onload = () => {
const secondGlobalThis = icw.globalThis;
const secondArray = icw.Array;
// The global object is different
console.log(icw.iframeName); // 'second'
console.log(secondArray === firstArray); // false
// But globalThis is still the same
console.log(firstGlobalThis === secondGlobalThis); // true
};
iframe.src = 'iframe.html?second';
};
</script>
File iframe.html
:
<script>
globalThis.iframeName = location.search.slice(1);
</script>
How do browsers ensure that globalThis
doesn’t change in this scenario? They internally distinguish two objects:
Window
is the global object. It changes whenever the location changes.WindowProxy
is an object that forwards all accesses to the currentWindow
. This object never changes.
In browsers, globalThis
refers to the WindowProxy
; everywhere else, it directly refers to the global object.