Know if a variable is a native object in javascript

Is there a way to find out if a variable passed to a function is a native object? I mean, I have a function that only needs its own 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 is a way to distinguish between native objects and everything else.

+2


a source to share


3 answers


You will need to do ===

(or !==

) against the list of accepted values ​​(which is not that long, from your question), realizing that it could be tricked into thinking something wasn't native that it was (just from another window).

But mostly:

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

      



Edit . Repeat my comment about things from other windows: keep in mind that constructors from one window are not ===

for constructors from another window (including iframe), for example:

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

      

alert "wnd.Array === Array? false" because Array

in is wnd

not the same as Array

in your current window, although both are built-in constructors for arrays.

+3


a source


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

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

      



This will give you a string that looks like "[object Array]".

Now, keep in mind what []

is an array instance and {}

is an object instance.

+2


a source


JavaScript can use an operator like "typeof".

alert (typeof arg)

      

Another (more complex) approach is to use

arg.prototype.constructor

      

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

0


a source







All Articles