I donβt understand why you are testing the constructor, I would just check the object directly to find out if it has a specific method.
Anyway, Gabriel is pretty close, but I would have done it differently:
function MyConstructor(){} MyConstructor.prototype.sampleMethod = function(){}; // Return true if instances of constructor have method // Return false if they don't // Return undefined if new constructor() fails function isDefined(constructor, method){ var temp, defined; try { temp = new constructor(); defined = !!(typeof temp[method] == 'function'); } catch(e) { // calling - new constructor - failed } return defined; } var foo; alert( isDefined(MyConstructor, 'sampleMethod') // Method on MyConstructor.prototype + '\n' + isDefined(MyConstructor, 'undefinedMethod') // Not defined + '\n' + isDefined(MyConstructor, 'toString') // Method on Object.prototype + '\n' + isDefined(foo, 'foo') // foo is not a constructor );
Of course, the above is only suitable for classical prototype inheritance using [[prototype]], something else is required when using a module template or similar (ie "inheritance" using closures).
source share