Check if an object has a user defined prototype?
Assuming you want to find out whether an object is an instance of a custom constructor function, you can just compare its prototype against Object.prototype
:
function hasUserPrototype(obj) {
return Object.getPrototypeOf(obj) !== Object.prototype;
}
Or if you maintain the constructor
property properly:
function hasUserPrototype(obj) {
return obj.constructor !== Object;
}
This would also work in browsers which don't support Object.getPrototypeOf
.
But both solutions would return true
also for other native objects, like functions, regular expressions or dates. To get a "better" solution, you could compare the prototype or constructor against all native prototypes/constructors.
Update:
If you want to test whether a function has a user defined prototype
value, then I'm afraid there is no way to detect this. The initial value is just a simple object with a special property (constructor
). You could test whether this property exists (A.prototype.hasOwnProperty('constructor')
), but if the person who set the prototype did it right, they properly added the constructor
property after changing the prototype.