views:

86

answers:

3

Hi, is there a way to know if a variable passed into a function is a native object? I mean, i have a function that requires only native objects as arguments, for every other type of variable it throws an error. So:

func(Array); //works
func(String); //works
func(Date); //works
func(Object); //works
...
func([]); //Throwr error
func({}); //Throws error

I want to know if there's a way to distinguish between native objects and everything else.

+4  A: 

You'd have to do an === (or !==) against the list of accepted values (which wouldn't be that long, from your question), being aware that that could be tricked into thinking something wasn't a native that was (just from another window).

But basically:

if (obj !== Array &&
    obj !== String &&
    obj !== Date &&
    /* ...and so on, there are only a few of them... */
   ) {
    throw "your error";
}

Edit Re my comment about things from other windows: Be aware that constructors from one window are not === to constructors from another window (including iframes), e.g.:

var wnd = window.open('blank.html');
alert("wnd.Array === Array? " + (wnd.Array === Array));

alerts "wnd.Array === Array? false", because the Array in wnd is not the same as the Array in your current window, even though both are built-in constructors for arrays.

T.J. Crowder
I didn't know that you can do that type of comparison, thanks. So i think that this is the only way right? There's no way to do a common check for every constructor?
mck89
@mck89: As far as I know, no, there's no shortcut way. (BTW, I edited my answer to explain the window thing better.)
T.J. Crowder
this is the most comprehensive answer I have ever received thanks:)
mck89
@mck89: LOL, no worries, glad that helped.
T.J. Crowder
+2  A: 

As far as I know, current "best practice" way to get the type of something is

var theType = Object.prototype.toString.call(theObject);

That'll give you a string that looks like "[object Array]".

Now, keep in mind that [] is an Array instance, and {} is an Object instance.

Pointy
If you try to to this with native objects you'll get always [object Function] beacause they are all functions, so there's no way to distinguish them because every other function has the same result
mck89
OK - I typed that under a misunderstanding of your question. Your question title asks about "native objects", when it seems that what you're really interested in is the set of constructor functions that create native objects. See Mr. Crowder's answer.
Pointy
A: 

There's a "typeof" operator in JavaScript that might help.

alert (typeof arg)

The other (a little more sophisticated) approach is to use

arg.prototype.constructor

this will give the reference to a function that was used to construct the object

Juriy