types in js

C

cognominal

I know that js is prototype based and not class based, that one can
dynamically add and remove properties and methodes in an object
and its prototype.

But I would like to be able to work in a more classy way (pun
unintended) and
ask the type of an object to know how to handle it.
For example, I would like to distinguish a mere array from an object

but typeof( [] ) and typeof( { key: "value" } both returns "object".
This is unsatisfying to me because they are certainly instances of a
different types
because I can do a push on the first and not on the second.

I could probably add a type property to the protype of my objects but I
would like to avoid to
badly redesign a wheel that certainly has already been done right
somewhere.
Can someone point me to a library?
Thanks in advance
 
I

Ivo

cognominal said:
typeof( [] ) and typeof( { key: "value" } both return "object".
This is unsatisfying to me because they are certainly instances
of different types
because I can do a push on the first and not on the second.

Well, checking for a method before using it is never a bad idea. This
so-called "feature detecting" is promoted on every js site you look at. But
in the case of arrays, who really are objects yes, you can also check the
'constructor' property.

if( typeof b==='object' && b.constructor===Array ) {
// b is an array, so we can push it!
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,794
Messages
2,569,641
Members
45,353
Latest member
RogerDoger

Latest Threads

Top