You could find this error by placing a breakpoint on the this.value = 0;
line, and examining this
; you will find that it is not what you expect.
The most robust solution is to rewrite your constructor to make sure it's being called with new
, using new.target
:
function CreateObject() {
if (!new.target) throw new TypeError('CreateObject() must be called with new');
this.value = 0;
}
const object = CreateObject();
Linters can help you find this type of error as well. For example, eslint has the new-cap option. It will complain if you call a non-capitalized function with new
, or call a capitalized function without new
. To take advantage of this, you'll have to follow the convention of capitalizing constructors, as in CreateObject
.
TypeScript (or ES6 as well) would report an error if you used class
and tried to instantiate it without new
:
class CreateObject {
value = 0;
once() { return this.value = 0; }
}
var x = CreateObject();
Value of type 'typeof CreateObject' is not callable. Did you mean to include 'new'?