Check if the object has a user defined prototype?

Simply put, can I check if the object has a prototype defined by the user?

Example

var A = function() {}; var B = function() {}; B.prototype = { }; // Pseudocode A.hasUserPrototype(); // False B.hasUserPrototype(); // True 

Is it possible?

+6
source share
3 answers

Assuming you want to know if an object is an instance of a custom constructor function, you can simply compare its prototype with Object.prototype :

 function hasUserPrototype(obj) { return Object.getPrototypeOf(obj) !== Object.prototype; } 

Or if you correctly save the constructor property:

 function hasUserPrototype(obj) { return obj.constructor !== Object; } 

This will also work in browsers that do not support Object.getPrototypeOf .

But both solutions will return true also for other native objects, such as functions, regular expressions or dates. To get the β€œbest” solution, you can compare the prototype or constructor with all of your own prototypes / constructors.


Update:

If you want to check if a function has a user-defined value of prototype , then I am afraid that it is impossible to detect. The initial value is a simple object with a special property ( constructor ). You can check if this property exists ( A.prototype.hasOwnProperty('constructor') ), but if the person who installed the prototype did it right, they correctly added the constructor property after changing the prototype.

+8
source

Felix King accurately considered the issue of inheritance, so I will consider the concept of existing properties

If you are just trying to check for the existence of a property called 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 processed as a hash map where other properties, such as hasOwnProperty , are hasOwnProperty , otherwise a safer way to check for the presence of a property is:

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

This can be turned into a general function like:

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

and is used as:

 has(a, 'prototype'); 
+1
source

For an object prototype, it will be undefined:

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

Source: https://habr.com/ru/post/945202/


All Articles