Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript isPrototypeOf vs instanceof usage

Tags:

javascript

Suppose we have the following:

function Super() {       // init code }  function Sub() {       Super.call(this);       // other init code }  Sub.prototype = new Super();  var sub = new Sub(); 

Then, in some other part of our ocde, we can use either of the following to check for the relationship:

sub instanceof Super;    

or

Super.prototype.isPrototypeOf( sub ) 

Either way, we need to have both the object (sub), and the parent constructor (Super). So, is there any reason why you'd use one vs the other? Is there some other situation where the distinction is more clear?

I've already carefully read 2464426, but didn't find a specific enough answer.

like image 403
user1689498 Avatar asked Aug 20 '13 19:08

user1689498


People also ask

What is isPrototypeOf in JavaScript?

isPrototypeOf() The isPrototypeOf() method checks if an object exists in another object's prototype chain.

How to check prototype of object in JavaScript?

The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.

What is Instanceof operator 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.

What is the prototype of console log?

log nor console are class constructors, so their prototype properties are undefined . Since undefined === undefined , console. log. prototype === console.


1 Answers

Imagine you don't use constructors in your code, but instead use Object.create to generate objects with a particular prototype. Your program might be architected to use no constructors at all:

var superProto = {     // some super properties }  var subProto = Object.create(superProto); subProto.someProp = 5;  var sub = Object.create(subProto);  console.log(superProto.isPrototypeOf(sub));  // true console.log(sub instanceof superProto);      // TypeError 

Here, you don't have a constructor function to use with instanceof. You can only use subProto.isPrototypeOf(sub).

like image 84
apsillers Avatar answered Sep 20 '22 20:09

apsillers