mck89
mck89

Reputation: 19241

Know if a variable is a native object in javascript

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.

Upvotes: 2

Views: 1760

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

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.

Upvotes: 3

Juriy
Juriy

Reputation: 5111

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

Upvotes: 0

Pointy
Pointy

Reputation: 413737

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.

Upvotes: 2

Related Questions