本页内容

字面量构造函数

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>
    }
}

数组的语义令人困惑

发生了什么?

Array 构造函数被用于处理多个参数。

为什么这样不好?

Array 构造函数的语义容易引起混淆:

  • new Array() 会创建一个空数组。
  • new Array(42) 创建一个包含 42 个元素的数组。
  • new Array(42, 43) 创建一个包含两个元素(42 和 43)的数组。

示例

import QtQuick

Item {
    function createArray() {
        return new Array(1, 2, 3)
    }
}

要解决此警告,请使用 `[...] ` 代替 `new Array(...)`。

函数:

import QtQuick

Item {
    function createArray() {
        return [1, 2, 3]
    }
}

© 2026 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.