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?
16
A literal construction function was used as a constructor.
17
18
\section2 Why is that bad?
19
Calling a literal construction function such as \c{Number} as a regular
20
function coerces the passed value to a primitive number. However, calling
21
\c{Number} as a constructor returns an object deriving from \c {Number}
22
containing that value. This is wasteful and likely not the expected outcome.
23
Moreover, it may lead to unexpected or confusing behavior because of the
24
returned value not being primitive.
25
26
\section2 Example
27
\qml
28
import QtQuick
29
30
Item {
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
44
To fix this warning, do not call these functions as constructors but as regular
45
functions:
46
\qml
47
import QtQuick
48
49
Item {
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
*/
qtdeclarative
src
qml
doc
src
qmllint
literal-constructor.qdoc
Generated on
for Qt by
1.14.0