js中typeof、instanceof与constructor

  公司没有老手带,基本所有东西都靠自己自学,所以导致学起来都是没有条理性的,比如说typeof、instanceof与constructor的区别到今天都搞不清楚,每次都需要重新去百度,所以在此系统学习下,这样下回再分不清时直接查阅自己的博客就OK了。

  typeof 返回一个表达式的数据类型的字符串,返回结果为js基本的数据类型,包括number,boolean,string,object,undefined,function. 语法为typeof(data) 或 typeof data。

  instanceof  则为判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例;返回boolean类型。 语法为 o instanceof A。

  

<script type="text/javascript">

 <!–

 alert("typeof(1):" + typeof(1));//number

 alert("typeof("abc"):" + typeof("abc"));//string

 alert("typeof(true):" +typeof(true));//boolean

 alert("typeof(2009-2-4):" + typeof(2009-2-4));//number

 alert("typeof("2009-2-4"):" + typeof("2009-2-4"));//string

 alert("typeof(m):" + typeof(m));//undefined

 var d=new Date();

 alert("typeof(d):" + typeof(d));//object

 function Person(){};

 alert("typeof(Person):" + typeof(Person));//function

 var a=new Array();

 alert("typeof(a):" + typeof(a));//object

 alert("a instanceof Array:" + (a instanceof Array));

 var h=new Person();

 var o={};

 alert("h instanceof Person:" + (h instanceof Person));//true

 alert("h instanceof Object:" + (h instanceof Object));//true

 alert("o instanceof Object:" + (o instanceof Object));//true

 alert(typeof(h));//object

 //–>

 </script>

使用typeof的一个不好的地方就是它会把Array还有用户自定义函数都返回为object。

<script type="text/javascript">

<!var j=2;

alert(typeof(j));//number

alert("j.constructor:" + j.constructor);//function …

alert(typeof(j.constructor));//function

//–>

</script>

可以看到js.constructor返回的是一些字符串,大家都应该能看到这是一个function类型,此例为Number()为Number对象的构造函数,Number()用于将其参数转换为数字number类型,并返回转换结果(若不能转换则返回 NaN)。

原文地址:https://www.cnblogs.com/dingdong/p/5075264.html