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.
a source to share
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.
a source to share