您的位置:首页 > Web前端 > JavaScript

JavaScript typeof()与instanceof()的区别

2012-04-07 13:50 591 查看
<script language="javascript">

/*

* typeof()来判断对象类型

* 对象,数组,null,返回值是object.

* 未定义,变量不存在,返回值是undefined.

*/

alert(typeof(123)); // 返回"number"

alert(typeof("123")); // 返回"string"

alert(typeof(true)); // 返回"boolean"

alert(typeof(new Object())); // 返回"object"

alert(typeof(new Function(""))); // 返回"function"

alert(typeof(undefined)); // 返回"undefined"

</script>

<script language="javascript">

/*

* instanceof()返回一个boolean值,指出对象是否是特定类的一个实例.

* 用来检测6种基本类型之一的object是不是某一对象(构造方法)产生的实例,回溯原型链.

* instanceof的内部机制是:每个实例都有_proto_隐藏属性,instanceof的时候会拿实例的_proto_属性与构造函数的prototype比较是否相同,js虚拟机正是通过这个_proto_链来查找的.

*/

var a = function () {};

var b = function () {};

b.prototype = new a;

var c = new b;

var d = new a;

alert(c instanceof a); // 返回true

alert(d instanceof a); // 返回true

alert(a instanceof Function); // 返回true

alert({} instanceof Function); // 返回false

a.prototype = {}; // 改变原型链

alert(c instanceof a); // 返回false

alert(d instanceof a); // 返回false

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: