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.
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.
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.
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
const obj1 = new Num();
const obj2 = Num(); // Noncompliant: undefined is returned, not an object
The rule checks that the new
operator is consistently used with each function’s invocations, meaning for all invocations or none.