Jim Buck
Jim Buck

Reputation: 2444

Is it possible to test if a javascript function is a constructor?

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;
}

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).

Upvotes: 1

Views: 169

Answers (1)

djechlin
djechlin

Reputation: 60788

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.

Upvotes: 1

Related Questions