Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 709
GriffLab Avatar asked May 16 '13 20:05

GriffLab


2 Answers

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.

like image 71
Felix Kling Avatar answered Sep 30 '22 06:09

Felix Kling


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');
like image 21
zzzzBov Avatar answered Sep 30 '22 07:09

zzzzBov