Why globalThis instead of something intuitive like globalObject, systemGlobal, or globalEntity?

Boris Zbarsky bzbarsky at mit.edu
Fri Oct 4 19:33:50 UTC 2019


On 10/4/19 2:39 PM, #!/JoePea wrote:
>> but the global `this` you captured still has the same identity as the new reference.
> 
> Interesting, I never knew that. Do you have a code sample to show how
> to detect or prove that?

Sure.  The following code logs "true, 5, 5, 5, 5, true, undefined, 
undefined, undefined, 5" in Firefox, Chrome, and Safari, which shows 
both the identity staying the same and the property disappearing from 
the WindowProxy, as well as showing the difference between the 
WindowProxy and the Window (the bareword lookup finds the var on the 
global, which is the Window, while `self.something` goes through the 
WindowProxy, which now points to the new `Window`):

<!DOCTYPE html>
<body>
   <script>
     var state = "first-load";
     var cachedThis;
     var cachedValueGetter;
     var cachedBarewordGetter;
     function loadHappened(iframe) {
       var win = iframe.contentWindow;

       if (state == "first-load") {
         cachedThis = win.getGlobalThis();
         cachedValueGetter = win.getPropertyValue;
         cachedBarewordGetter = win.getBareword;
         console.log(win == cachedThis);
         console.log(win.something);
         console.log(cachedThis.something);
         console.log(cachedValueGetter());
         console.log(cachedBarewordGetter());
         state = "second-load";
         iframe.srcdoc = iframe.srcdoc.replace("var something = 5;", "");
         return;
       }

       console.log(frames[0] == cachedThis);
       console.log(frames[0].something);
       console.log(cachedThis.something);
       console.log(cachedValueGetter());
       console.log(cachedBarewordGetter());
     }
   </script>
   <iframe srcdoc="
      <script>
        var self = this;
        var something = 5;
        function getGlobalThis() {
          return self;
        }
        function getPropertyValue() {
          return self.something;
        }
        function getBareword() {
          return something;
        }
      </script>"
      onload="loadHappened(this)"></iframe>
</body>

-Boris


More information about the es-discuss mailing list