类型判断常用的的四种方式

mac2022-06-30  37

  1.typeof

    能正确判断出null以外的原始类型(对象类型的判断就有点感人了)

    判断null会出错:

  2.instanceof

    a instanceof b

    能较为准确的判断出对象类型,但无法判断原始类型

    原理:通过查找b是否在a的原型链上

    

  3.constructor(通过判断是否某个构造函数的实例)

 

  4.toString(建议使用Object.prototype.toString.call(),因为toString方法可能被重写,无法达到最好的效果)

    

 

转载于:https://www.cnblogs.com/angle-xiu/p/11300697.html

最新回复(0)