Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript checking object prototype

Is there any difference between following pieces of code:

inst instanceof Constr

and

inst.__proto__ === Constr.prototype

for example:

var xyz = {}
xyz instanceof Object

and

xyz.__proto__ === Object.prototype

? If so, what is the difference, which one is the preferred?

like image 616
ducin Avatar asked Jun 07 '26 11:06

ducin


1 Answers

__proto__ isn't part of the ECMAScript 5 specification, and you have no guarantee of future support. The standard ways to access the prototype of an object are to access the prototype of the constructor or, better, Object.getPrototypeOf (but this doesn't work on IE8).

instanceof checks the prototype of the constructor but also "tests presence of constructor.prototype in object prototype chain.".

If your goal is to check if an object is an instance of a specific class, and it's OK for you if it's not a direct instance, then you should use the instanceof operator : it's really just made for that.

like image 107
Denys Séguret Avatar answered Jun 10 '26 08:06

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!