1

I'd like to test if a function is a constructor (meant to be called with new), or just a regular function that should be called literally.

This very well may not be possible, I could not find anything on the matter, but wanted to see if it is possible simply for the sport of it.

Here is the basic check that I have so far:

function isConstructor(func) {
  // Ensure it is a function...
  if (typeof func !== 'function') {
    return false;
  }

  // Check for at least one custom property attached to the prototype
  for (var prop in func.prototype) {
    if (func.prototype.hasOwnProperty(prop)) {
      return true;
    }
  }

  // No properties were found, so must not be a constructor.
  return false;
}
  • Is this a decent approximation?
  • Is there anything else I can check for?
  • What drawbacks/false positives exist for this approach?

NOTE: This is a question of curiosity, not requirement. Please don't say "that's a bad unit test" or "is it really worth it?". This is simply a fun exercise to see what is possible (albeit bad/unreasonable/not-to-be-used).

Jim Buck
  • 2,383
  • 23
  • 42
  • 1
    Any function in JavaScript *can* be a constructor. There's really no way to tell. Checking the prototype can get you lots of false negatives. – Pointy Mar 31 '15 at 17:32
  • @Pointy What are those drawbacks? I'm not asking _yes_ or _no_, I'm asking _how_ or _why not_. I expect that there is no way to do it, but my question is what is the closest way to do it, if any. If there truly is no way, then create an answer instead of a comment and explain why. – Jim Buck Mar 31 '15 at 17:45
  • Well it depends; if you're OK with your code telling you that some number of functions that actually are used as constructors are *not* constructors, then by all means go for it. – Pointy Mar 31 '15 at 17:49
  • The reason I'm commenting and not answering is that your question is ambiguous. *Why* do you want to know this? What is your overall goal? If you're just wondering, then it's kind-of a matter of opinion on how or if anybody "should" do this. – Pointy Mar 31 '15 at 17:50

1 Answers1

1

It's not possible because any function in Javascript can be a constructor. You may call any function prefaced with new to have its this point to a new object, just like you may .call any function to have its this point to anything you want.

djechlin
  • 59,258
  • 35
  • 162
  • 290