69 lines
2.1 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
JavaScript has the ``++new++`` keyword that is used in conjunction with constructor functions to create new instances of objects. When you use the ``++new++`` keyword with a function, it signifies that the function is intended to be used as a constructor function to create objects.
Any function can be used as a constructor function by convention. Constructor functions are used to create new objects with the same structure or properties. They are typically named with an initial capital letter to distinguish them from regular functions.
2021-04-28 16:49:39 +02:00
[source,javascript]
----
function Person(name, age) {
this.name = name;
this.age = age;
}
----
To create a new instance of an object using the constructor function, you use the ``++new++`` keyword before the function call.
[source,javascript]
----
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
----
Constructor functions, which create new object instances, must only be called with ``++new++``. Non-constructor functions must not. Mixing these two usages could lead to unexpected results at runtime.
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
function getNum() {
return 5;
}
function Num(numeric, alphabetic) {
this.numeric = numeric;
this.alphabetic = alphabetic;
}
const num1 = getNum();
const num2 = new getNum(); // Noncompliant: An empty object is returned, not 5
2021-04-28 16:49:39 +02:00
const obj1 = new Num();
const obj2 = Num(); // Noncompliant: undefined is returned, not an object
2021-04-28 16:49:39 +02:00
----
The rule checks that the ``++new++`` operator is consistently used with each function's invocations, meaning for all invocations or none.
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new[``++new++`` operator]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Correct the use of this function; on line n it was called [with|without] "new".
=== Highlighting
* primary: 1st inconsistent function call
* secondary: previous function call with different syntax
** message: Called [with|without] "new"
endif::env-github,rspecator-view[]