3

If I have function:

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

Is there a way to know if invoked by:

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

versus:

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

1 Answers1

3

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"!

Nebula
  • 6,614
  • 4
  • 20
  • 40
  • @whatwasthat I believe that kind of defensive programming should be avoided. Using tools to control code quality, such as jshint would warn about those errors automatically. – plalx Jul 15 '15 at 23:57