Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-95677

Using `this` within arrow function expressions within class methods can point to wrong `this`

    XMLWordPrintable

Details

    • Linux/Wayland
    • 63f71197ca7b0a5527fb7afa6dd42885b80606b1

    Description

      Hey there. I've identified a problem with how this is handled when used in arrow function expressions in ES6 class methods. It only occurs when the arrow function expression creates another scope within its body (for example using a if-statement). I've created the following PoC to demonstrate the issue:

      // engine.* methods are from C++. snippet below replicates its behavior in a NodeJS environment
      let engine = {};
      engine.beginTimer = function(delay, func, oneshot) {
          if (oneshot) {
              setTimeout(func, delay);
          } else {
              setInterval(func, delay);
          }
      }
      
      
      var globalThis = this;
      
      class Foo {
          constructor() {
              (() => {
                  console.debug(this instanceof Foo); // true (QJSEngine & NodeJS)
                  if (true) {
                      console.debug(this); // undefined (QJSEngine); "Foo { prop: 'prop' }" (NodeJS)
                  }
              })();
              engine.beginTimer(100, () => {
                  console.debug(this instanceof Foo);  // true (QJSEngine & NodeJS)
                  if (true) {
                      console.debug(this.globalThis === this); // true (QJSEngine); false (NodeJS)
                  }
              }, true);
          }
      }
      
      

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              ulherman Ulf Hermann
              swiftb0y Nikolaus Einhauser
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Gerrit Reviews

                  There are no open Gerrit changes