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\ingroup qmllint-warnings-and-errors
6
7\title Literal constructor
8\brief [literal-constructor] Do not use function as a constructor.
9
10\qmllintwarningcategory literal-constructors
11
12\section1 Do not use function as a constructor
13
14\section2 What happened?
15A literal construction function was used as a constructor.
16
17\section2 Why is that bad?
18Calling a literal construction function such as \c{Number} as a regular
19function coerces the passed value to a primitive number. However, calling
20\c{Number} as a constructor returns an object deriving from \c {Number}
21containing that value. This is wasteful and likely not the expected outcome.
22Moreover, it may lead to unexpected or confusing behavior because of the
23returned value not being primitive.
24
25\section2 Example
26\qml
27import QtQuick
28
29Item {
30 function numberify(x) {
31 return new Number(x)
32 }
33 Component.onCompleted: {
34 let n = numberify("1")
35 console.log(typeof n) // object
36 console.log(n === 1) // false
37
38 if (new Boolean(false)) // All objects are truthy!
39 console.log("aaa") // aa
40 }
41}
42\endqml
43To fix this warning, do not call these functions as constructors but as regular
44functions:
45\qml
46import QtQuick
47
48Item {
49 function numberify(x) {
50 return Number(x)
51 }
52 Component.onCompleted: {
53 let n = numberify("1")
54 console.log(typeof n) // number
55 console.log(n === 1) // true
56
57 if (Boolean(false))
58 console.log("aaa") // <not executed>
59 }
60}
61\endqml
62
63\section1 Array has confusing semantics
64
65\section2 What happened?
66An \c Array constructor was used with more than one argument.
67
68\section2 Why is that bad?
69The \c{Array} constructor has confusing semantics:
70\list
71\li \c{new Array()} creates an empty array.
72\li \c{new Array(42)} creates an array with 42 elements.
73\li \c{new Array(42, 43)} creates an array with two elements, 42 and 43.
74\endlist
75
76\section2 Example
77\qml
78import QtQuick
79
80Item {
81 function createArray() {
82 return new Array(1, 2, 3)
83 }
84}
85\endqml
86
87To fix this warning, use \c{[...]} instead of \c{new Array(...)}.
88
89functions:
90\qml
91import QtQuick
92
93Item {
94 function createArray() {
95 return [1, 2, 3]
96 }
97}
98\endqml
99*/