リテラルコンストラクタ
この警告カテゴリーはqmllintによって[literal-constructors]
。
コンストラクタとして関数を使用しないでください。
何が起こったのですか?
リテラル構築関数がコンストラクタとして使用されました。
なぜ悪いのですか?
Number
のようなリテラル構築関数を通常の関数として呼び出すと、渡された値はプリミティブ数に強制されます。しかし、Number
をコンストラクタとして呼び出すと、その値を含むNumber
から派生したオブジェクトが返されます。これは無駄であり、期待された結果ではない可能性が高い。さらに、返される値がプリミティブでないため、予期しない動作や混乱を招く可能性があります。
例
import QtQuick Item { function numberify(x) { return new Number(x) } Component.onCompleted: { let n = numberify("1") console.log(typeof n) // object console.log(n === 1) // false if (new Boolean(false)) // All objects are truthy! console.log("aaa") // aa } }
この警告を修正するには、これらの関数をコンストラクタとして呼び出さず、通常の関数として呼び出します:
import QtQuick Item { function numberify(x) { return Number(x) } Component.onCompleted: { let n = numberify("1") console.log(typeof n) // number console.log(n === 1) // true if (Boolean(false)) console.log("aaa") // <not executed> } }
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.