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