Determining if an object can be constructed

Scott Sauyet scott at
Fri Jan 20 03:03:46 UTC 2017

Michael Haufe <tno at> wrote:
> The question came up recently on CLJS [1] on how to determine if an object
> is safe to call as a Constructor.

The original question was a response to

|| You cannot determine whether a function can be called as a constructor
|| unless you try it.

that asked the more specific question

| What would count as positive evidence that a function can actually be
| called *reasonably* as a constructor function?

I was wondering if there was any way to distinguish a function like this

    var fn = (function() {
      var g = {};
      return function() {return g;};

which will pass all the proposed tests here, but still does not
actually serve as a constructor function as is made clear by

    // no errors here
    var obj1 = new fn();
    var obj2 = new fn(); = 'bar'
    obj2; //=> {foo: 'bar'}

Without defining constructor functions explicitly, one would certainly
hope that they would create new objects on each invocation, that there
is some sort of difference between constructor functions and factory

I wasn't really expecting there to be a positive answer.  But I was
curious and raised the issue.  (For all I know, this is wandering into
issues similar to the Halting Problem.)

But does anyone have a suggestion for a test that would reliably tell
whether a function can serve as a true constructor in this manner?

  -- Scott

More information about the es-discuss mailing list