JavaScript中判断一个对象是否为一个类的实例

JavaScript中判断一个对象 是否为一个类的实例主要有两种方法,即instanceof和constructor,前者的用法是:


返回一个boolean值,指出对象是否为特定类的一个实例。后者的用法是:

<pre class="lang:javascript decode:true"]object.constructor

表示创建对象的函数。

两者的区别通过下面的代码可以看出来:

var a = [1, 2, 3];
alert(a instanceof Array);  //返回true
alert(a instanceof Object);  //返回true

alert(a.constructor == Array);  //返回true
alert(a.constructor == Object);  //返回false

如上可见,constructor 更加精确地指向对象所属的类,而对 instanceof 而言,即使是父类也会返回true。

2 Replies to “JavaScript中判断一个对象是否为一个类的实例”

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s