Try something like this:
function Thing(nameOfThing) {
if (this == window) throw new Error("Must be constructed with new!");
this.name = nameOfThing;
}
var myThing = new Thing("Something"); // Thing {name: "Something"}
var myThing = Thing("Something"); // error
Basically we're comparing this
with the global window
object. If they are the same (hence ==
) then throw an error if they are the same.
You could also figure it out by checking if this
is an instance of Thing
:
function Thing(nameOfThing) {
if (!(this instanceof Thing)) throw new Error("Must be instance of Thing!");
this.name = nameOfThing;
}
This is slightly better because it will only allow any instance of Thing
or an instance of a child class of Thing
.
It's a very good idea you remembered to keep this in mind because otherwise you'll be setting attributes of window
- so window.name
will be "Something"
!