In a JavaScript function, how can I know if I have been called with a new one?
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
We are mainly comparing this
to a global object window
. If they are the same (hence ==
) then throw an error if they are the same.
You can also figure it out by checking if an this
instance is 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 Thing
or instance of the child class Thing
.
This is a very good idea that you keep in mind to keep this in mind, because otherwise you will be setting attributes window
- so it window.name
will "Something"
!
source to share