86 lines
2.6 KiB
Plaintext
86 lines
2.6 KiB
Plaintext
== 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.
|
|
|
|
To create a new instance of an object using the constructor function, you use the ``++new++`` keyword before the function call.
|
|
|
|
The ``++new++`` keyword should only be used with objects that define a constructor function. Attempting to use it with an object or a variable that is not a constructor will raise a ``++TypeError++``.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
function MyClass() {
|
|
this.foo = 'bar';
|
|
}
|
|
|
|
const someClass = 1;
|
|
|
|
const obj1 = new someClass; // Noncompliant: someClass is a variable
|
|
const obj2 = new MyClass(); // Noncompliant if parameter considerJSDoc is true. Compliant when considerJSDoc is false
|
|
----
|
|
|
|
Always use the ``++new++`` keyword with constructor functions or classes.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
/**
|
|
* @constructor
|
|
*/
|
|
function MyClass() {
|
|
this.foo = 'bar';
|
|
}
|
|
|
|
const someClass = function(){
|
|
this.prop = 1;
|
|
}
|
|
|
|
const obj1 = new someClass;
|
|
const obj2 = new MyClass();
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new[``++new++`` operator]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Constructor[Constructor]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_constructor[`TypeError: "x" is not a constructor`]
|
|
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Replace {0} with a constructor function.
|
|
|
|
|
|
=== Parameters
|
|
|
|
.considerJSDoc
|
|
****
|
|
|
|
----
|
|
false
|
|
----
|
|
|
|
Consider only functions with @constructor tag as constructor functions
|
|
****
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 4 Jun 2015, 10:25:23 Elena Vilchik wrote:
|
|
\[~ann.campbell.2] Assign to you for validation and completion (labels, SQALE). CC [~linda.martin]
|
|
|
|
=== on 4 Jun 2015, 13:25:48 Ann Campbell wrote:
|
|
\[~elena.vilchik] I've made some changes to the description and to the comments in the code samples. Please double-check me.
|
|
|
|
endif::env-github,rspecator-view[]
|