Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
literal-constructor.qdoc
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5\page qmllint-warnings-and-errors-literal-constructor.html
6\ingroup qmllint-warnings-and-errors
7
8\title Literal constructor
9\brief [literal-constructor] Do not use function as a constructor.
10
11\qmllintwarningcategory literal-constructors
12
13\section1 Do not use function as a constructor
14
15\section2 What happened?
16A literal construction function was used as a constructor.
17
18\section2 Why is that bad?
19Calling a literal construction function such as \c{Number} as a regular
20function coerces the passed value to a primitive number. However, calling
21\c{Number} as a constructor returns an object deriving from \c {Number}
22containing that value. This is wasteful and likely not the expected outcome.
23Moreover, it may lead to unexpected or confusing behavior because of the
24returned value not being primitive.
25
26\section2 Example
27\qml
28import QtQuick
29
30Item {
31 function numberify(x) {
32 return new Number(x)
33 }
34 Component.onCompleted: {
35 let n = numberify("1")
36 console.log(typeof n) // object
37 console.log(n === 1) // false
38
39 if (new Boolean(false)) // All objects are truthy!
40 console.log("aaa") // aa
41 }
42}
43\endqml
44To fix this warning, do not call these functions as constructors but as regular
45functions:
46\qml
47import QtQuick
48
49Item {
50 function numberify(x) {
51 return Number(x)
52 }
53 Component.onCompleted: {
54 let n = numberify("1")
55 console.log(typeof n) // number
56 console.log(n === 1) // true
57
58 if (Boolean(false))
59 console.log("aaa") // <not executed>
60 }
61}
62\endqml
63*/