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

{{this}} becomes invalid in block in closure in {{map}}

    XMLWordPrintable

Details

    • All

    Description

      Relevant code inside main.qml:

              [0].map(index => {
                          console.assert(this, "Totally fine");
                          {
                              console.assert(this, "Not fine");
                          }
                      });
      

      Actual output:

      Not fine
       (qrc:/main.qml:8)
      onCompleted (qrc:/main.qml:5)

      Expected output: Empty

      Opening a block inside a closure inside map seems to make this undefined. That is inconsistent with other JS engines. Loops and the lambda without map do not show this behavior.

      The other files outside main.qml are for project setup.

      You can also test it online with the code

      import QtQuick 2.7
      import QtQuick.Controls 2.3
      
      Text {
          text: {
              return [0].map(index => {
                  if (this) {
                      if (this) {
                          return "Level 2";
                      }
                      return "Level 1";
                  }
                  return "Level 0";
                  }).join();
          }
      }

      at https://qmlonline.kde.org which should display "Level 2" but displays "Level 1" instead.

      Workaround:
      Put

      const self = this;
      

      at the start of the closure block and then use self instead of this.

      Attachments

        1. CMakeLists.txt
          0.4 kB
          Toe Ger
        2. main.cpp
          0.2 kB
          Toe Ger
        3. main.qml
          0.3 kB
          Toe Ger
        4. qml.qrc
          0.1 kB
          Toe Ger
        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            qtqmlteam Qt Qml Team User
            toeger Toe Ger
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes