Consider such an object with a prototype chain:
var A = {}; var B = Object.create(A); var C = Object.create(B);
How to check in runtime if C has A in its prototype chain?
instanceof
doesn't fit as it's designed to work with constructor functions, which I'm not using here.
Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.
prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.
The Typescript instanceof is one of the operators, and it is used to determine the specific constructor, and it will be creating the object of the classes. It will call the methods with the help of instance like that if we use an interface that can be implemented and extended through the classes.
The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.
My answer will be short…
You could use the isPrototypeOf
method, which will be present in case your object inherits from the Object prototype, like your example.
example:
A.isPrototypeOf(C) // true B.isPrototypeOf(C) // true Array.prototype.isPrototypeOf(C) // false
More info can be read here: Mozilla Developer Network: isPrototypeOf
You could iterate back through the prototype chain by calling Object.getPrototypeOf
recursively: http://jsfiddle.net/Xdze8/.
function isInPrototypeChain(topMost, itemToSearchFor) { var p = topMost; do { if(p === itemToSearchFor) { return true; } p = Object.getPrototypeOf(p); // prototype of current } while(p); // while not null (after last chain) return false; // only get here if the `if` clause was never passed, so not found in chain }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With