Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instanceof equivalent for Object.create and prototype chains

Tags:

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.

like image 735
Kos Avatar asked Dec 09 '11 17:12

Kos


People also ask

What is prototype and prototype chaining?

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.

What is difference between __ proto __ and prototype?

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.

How does Instanceof work in typescript?

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.

What is instance of an object in JavaScript?

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.


2 Answers

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

like image 85
Couto Avatar answered Sep 23 '22 07:09

Couto


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 } 
like image 28
pimvdb Avatar answered Sep 23 '22 07:09

pimvdb