Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: (JavaScript): How often have you needed instanceOf and/or isProtoTypeOf?
3 points by nni on Feb 11, 2015 | hide | past | favorite | 3 comments
I'm not questioning the utility of these, I'm just curious how often in day-to-day practice folks end up needing them.



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're doing:

if (obj instanceof Foo) obj.doSomething(); else if (obj instanceof Bar) obj.doSomethingElse();

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.

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.


I would think that it depends on how structured your code needs to be. For example, I'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.


I've only ever used it to check if a given variable contains an Array. Seems to be the easiest way.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: