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'?
var x = new createObject();to instantiate an object instead of just calling the functionnewkeyword. There's some more good practices associated with the pattern at this question.createObjectactually makes the function sound like a function that creates an object - which you would expect to call without thenewkeyword - this doesn't address your problem, but it's probably something to keep in mindnew(ignoring error-checking) by following it!