JS 类型检测

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

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

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

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

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

一.typeof( xxx)  || typeof  xxxspa

typeof   2            输出   number.net

typeof   '222'                  输出    stringprototype

typeof  true                    输出     booleanhtm

typeof    undefined          输出  undefined对象

typeof   (function(){})    输出  function

typeof   null         输出   object

typeof   {}           输出   object

typeof    []           输出   object

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

2、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

3、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;}

4、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

相关文章
相关标签/搜索