JS 类型检测

PS:慕课心得(爱学习的妹纸,运气不会太差?)

首先我们要先了解JS中的类型有哪些(每个人看到的文档不同,对类型的分类可能会有不同,以下是个人的理解)?

  1.原始类型:String Number Boolean Undefined Null

  2.引用类型:Function(特殊) Object Array ....(除原始类型外的都是引用类型)

如此多的类型,在使用的时候如何是检测就成了一个很严肃的问题,因些下面对类型的检测做了出归类,但愿对你有帮助:

一.typeof( xxx)  || typeof  xxx

typeof   2            输出   number

typeof   '222'                  输出    string

typeof  true                    输出     boolean

typeof    undefined          输出  undefined

typeof   (function(){})    输出  function

typeof   null         输出   object

typeof   {}           输出   object

typeof    []           输出   object

由上述示例不难看出,typeof 能检测的类型还是有限的,除 Null 以外的原始类型的检测还算准确,而引用类型只能正确检测出 Function ,因些引出 instanceof 来弥补 typeof 检测时遗留的漏洞

二、xxx instanceof Object 

instance,故名思义,实例,例子,所以instanceof 用于判断一个变量是否是某个对象的实例

var a=[];
console.log(a instanceof Array) //返回true 

另外,更重的一点是 instanceof 可以在继承关系中用来判断一个实例是否属于它的父类型。

例  function Foo(){}
  Foo.prototype = new Aoo();//JavaScript 原型继承
  var foo = new Foo();
  console.log(foo instanceof Foo)//true
  console.log(foo instanceof Aoo)//true

上面的代码中是判断了一层继承关系中的父类,在多层继承关系中,instanceof 运算符同样适用。

instanceof   参考:http://www.studyofnet.com/news/175.html

三、constructor

在W3C定义中的定义:constructor 属性返回对创建此对象的数组函数的引用

就是返回对象相对应的构造函数。从定义上来说跟instanceof不太一致,但效果都是一样的

如: (a instanceof Array)   //a是否Array的实例?true or false

   (a.constructor == Array)  // a实例所对应的构造函数是否为Array? true or false

function employee(name,job,born){
    this.name=name;
    this.job=job;
    this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
console.log(bill.constructor); //function employee(name, jobtitle, born){this.name = name; this.jobtitle = job; this.born = born;}

四、Object.prototype.toString.call()

可以说这个方法是最简单的方法,之所以说它简单,是因为这个检测方法能检测出任何类型,所以作为一个很懒的程序猿,我选择只记这个最简单的方法,就是这么任性(手动骄傲表情)

 我们来试试这个玩儿意儿:

var   gettype=Object.prototype.toString

        gettype.call('aaaa')           输出      [object String]

        gettype.call(2222)            输出      [object Number]

        gettype.call(true)             输出      [object Boolean]

        gettype.call(undefined)     输出      [object Undefined]

        gettype.call(null)                  输出   [object Null]

         gettype.call({})                   输出   [object Object]

         gettype.call([])                    输出   [object Array]
         gettype.call(function(){})     输出   [object Function]

 对于这种方法,以下有几个链接可供参考解释:

http://blog.csdn.net/zhangw428/article/details/4171630

http://my.oschina.net/sfm/blog/33197

http://openxtiger.iteye.com/blog/1893378

posted @ 2016-12-05 16:19  菜鸟提升记  阅读(485)  评论(0编辑  收藏  举报