开发者

Know if a variable is a native object in javascript

is there a way t开发者_如何学Co 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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜