Connecting Tech Pros Worldwide Forums | Help | Site Map

types in js

cognominal
Guest
 
Posts: n/a
#1: Feb 17 '06
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

--
cognominal stef


VK
Guest
 
Posts: n/a
#2: Feb 17 '06

re: types in js



cognominal wrote:[color=blue]
> 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[/color]

var arr = new Array();

if (arr instanceof Array) {
alert("I am array!");
}

Ivo
Guest
 
Posts: n/a
#3: Feb 17 '06

re: types in js


"cognominal" <cognominal@gmail.com> wrote[color=blue]
> 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.[/color]

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!
}

--
hth
ivo
http://www.yorick.onlyfools.com/


Closed Thread