typeof 返回值有六种可能: "number," "string," "boolean," "object," "function," 和 "undefined."
instanceof返回一个 Boolean 值,指出对象是否是特定类的一个实例

Javascript 的 typeof可以获取变量的类型
有如下6种返回值:
1)number;
2)string;
3)boolean;
4)object;
5)function;
6)undefined.   

instanceof 用来检测6中基本类型之一Object是不是某一个构造方法产生的实例,回溯原型链。

typeof效率比较高 
instanceof 适用的范围很广

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
<title>jstest2</title> 
<script type="text/javascript"> 
       var array1= new Array(); 
       var array2=['china','usa','uk']; 
       var string ="ddd"; 
       var string1=new String(); 
       var obj={}; 
      var number=2323; 
   function test(array,string){ 
     if(typeof array=='object'&&typeof string=='object'){ 
         alert("all objects"); 
         } 
    else if(typeof array!='object'){ 
         alert("1 not object"); 
         if(array instanceof Array){ 
            alert("1:array") 
         } 
    else if(array instanceof String){ 
         alert("1:string") 
          } 
      else{  
        alert("1:may number"); 
           } 
  
      }  
    else if(typeof string!='object') { 
                 alert("2 not object!"); 
      if(string instanceof Array){ 
               alert("2:array"); 
           } 
    else if(string instanceof String){ 
                 alert("2:string"); 
             } 
     else{ 
           alert("2:may number!"); 
           } 
     } 
   else{ 
        alert("2 not object!"); 
      } 
   } 
 function checkfun(){ 
    if(getrealtype instanceof Function){ 
         alert(true); 
      } 
  } 
  function persons(name,dd,dd){ 
    } 
   var person = new persons('ddd','343','434'); 
   var checkperson=function (){ 
   var testperson =new persons('dd','dd','dd'); 
        if(testperson instanceof persons){ 
             alert("righttrue!"); 
        }   
   } 
function getrealtype(){ 
   test(array1,array2); 
   test(array1,string); 
    test(string,string1); 
       checkfun(); 
       checkperson(); 
 } 
  
</script> 
</head> 
<body> 
 <input type="button" onclick="javascript:getrealtype()" value="getrealtype" /> 
</body> 
</html>

转载于:https://my.oschina.net/keejun/blog/126338

更多推荐