diff options
author | Ulf Hermann <ulf.hermann@qt.io> | 2022-02-01 16:26:42 +0100 |
---|---|---|
committer | Qt Cherry-pick Bot <cherrypick_bot@qt-project.org> | 2022-02-02 15:29:57 +0000 |
commit | 63f71197ca7b0a5527fb7afa6dd42885b80606b1 (patch) | |
tree | c44b9d0ae0cc5138a25a30b9e22ba236ab51ce18 | |
parent | 22a16128a19ea78f5f5f415dcb8cb0cd84ca3e00 (diff) |
JavaScript: Make "this" available in blocks inside arrow functions
Fixes: QTBUG-98039
Change-Id: I51ff36994fa0f3f3568c8114cb6841f677f64bc4
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
(cherry picked from commit eeec9f03e9cf57e8cde311897f7e3e62a217da15)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
-rw-r--r-- | src/qml/compiler/qv4codegen.cpp | 15 | ||||
-rw-r--r-- | tests/auto/qml/qjsengine/tst_qjsengine.cpp | 22 |
2 files changed, 32 insertions, 5 deletions
diff --git a/src/qml/compiler/qv4codegen.cpp b/src/qml/compiler/qv4codegen.cpp index fd55ce5562..20685e42f1 100644 --- a/src/qml/compiler/qv4codegen.cpp +++ b/src/qml/compiler/qv4codegen.cpp @@ -3065,12 +3065,17 @@ bool Codegen::visit(ThisExpression *) if (hasError()) return false; - if (_context->isArrowFunction) { - Reference r = referenceForName(QStringLiteral("this"), false); - r.isReadonly = true; - setExprResult(r); - return false; + for (Context *parentContext = _context; parentContext; parentContext = parentContext->parent) { + if (parentContext->isArrowFunction) { + Reference r = referenceForName(QStringLiteral("this"), false); + r.isReadonly = true; + setExprResult(r); + return false; + } + if (parentContext->contextType != ContextType::Block) + break; } + setExprResult(Reference::fromThis(this)); return false; } diff --git a/tests/auto/qml/qjsengine/tst_qjsengine.cpp b/tests/auto/qml/qjsengine/tst_qjsengine.cpp index c2abf83308..fb85be334e 100644 --- a/tests/auto/qml/qjsengine/tst_qjsengine.cpp +++ b/tests/auto/qml/qjsengine/tst_qjsengine.cpp @@ -279,6 +279,7 @@ private slots: void uiLanguage(); void urlObject(); + void thisInConstructor(); public: Q_INVOKABLE QJSValue throwingCppMethod1(); @@ -5470,6 +5471,27 @@ void tst_QJSEngine::urlObject() QCOMPARE(result2, url); } +void tst_QJSEngine::thisInConstructor() +{ + QJSEngine engine; + const QJSValue result = engine.evaluate(R"((function() { + let a = undefined; + class Bugtest { + constructor() { + (() => { + if (true) { + a = this; + } + })(); + } + }; + new Bugtest(); + return a; + })())"); + QVERIFY(!result.isUndefined()); + QVERIFY(result.isObject()); +} + QTEST_MAIN(tst_QJSEngine) #include "tst_qjsengine.moc" |