GriffLab
GriffLab

Reputation: 2166

Check if an object has a user defined prototype?

Simply put can I check if an object has a user defined prototype?

Example;

var A = function() {};

var B = function() {};

B.prototype = {

};

// Pseudocode
A.hasUserPrototype(); // False
B.hasUserPrototype(); // True

Is this possible?

Upvotes: 9

Views: 10612

Answers (3)

Felix Kling
Felix Kling

Reputation: 816452

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.

Upvotes: 13

zzzzBov
zzzzBov

Reputation: 179046

Felix King accurately addressed the issue of inheritance, so I will address the concept of existing properties instead

If you're simply trying to check for the presence of a property named prototype on an object, you can use:

a.hasOwnProperty('prototype')

This will return true for:

a = {
    //the object has this property, even though
    //it will return undefined as a value
    prototype: undefined 
};

This assumes that the object is not being treated as a hashmap, where other properties, such as hasOwnProperty have been set, otherwise, a safer way of checking for the presence of a property is:

Object.prototype.hasOwnProperty.call(a, 'prototype')

This can be turned into a generic function as:

has = (function (h) {
    "use strict";
    return function (obj, prop) {
        h.call(obj, prop);
    };
}(Object.prototype.hasOwnProperty));

and used as:

has(a, 'prototype');

Upvotes: 1

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

For A object prototype will be undefined:

typeof A.prototype == "undefined" // true
typeof B.prototype == "undefined" // false

Upvotes: 0

Related Questions