字面构造函数

此警告类别由 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.