In a JavaScript function, how can I know if I have been called with a new one?

If I have a function:

function Thing( name_of_thing )
{
    this.name = name_of_thing;
}

      

Is there a way to find out if it was caused by:

var my_thing = new Thing( 'Something' ); // result: { name: "Something" }

      

against

var my_thing = Thing( 'Something' ); // result: undefined

      

+3


source to share


1 answer


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"

!

+3


source







All Articles