TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Ask HN: (JavaScript): How often have you needed instanceOf and/or isProtoTypeOf?

3 pointsby nniover 10 years ago
I'm not questioning the utility of these, I'm just curious how often in day-to-day practice folks end up needing them.

3 comments

marcofisetover 10 years ago
Most of the time, I consider the use of instanceof as a code smell. You could easily replace the type checking with a polymorphic method call. For example, say you&#x27;re doing:<p>if (obj instanceof Foo) obj.doSomething(); else if (obj instanceof Bar) obj.doSomethingElse();<p>In that case, if it makes sense for Foo and Bar to share a common ancestor, the ideal thing would be to have a doSomething function on the parent class (or parent prototype in javascript), which is overridden in both Foo and Bar, therefore making the type checking unnecessary. Simply call doSomething on the object.<p>You should note that this is not applicable to every situation, but it should take care of most cases where you would need to use instanceof.
coreyp_1over 10 years ago
I would think that it depends on how structured your code needs to be. For example, I&#x27;m working on a soon-to-be open source project which makes heavy use of prototypical inheritance, so I use it a lot. That being said, for one-off projects that do not require a lot of extensibility, you might not use it at all.
Spoomover 10 years ago
I&#x27;ve only ever used it to check if a given variable contains an Array. Seems to be the easiest way.