美文网首页
数据类型判断

数据类型判断

作者: fuheideMayuyu | 来源:发表于2018-10-22 15:08 被阅读0次

    typeof:

    使用typeof可以判断除了null之外所有数据类型,但是

    typeof null // 'object'
    

    这是因为在js最初版本中使用的32位系统,出于性能考虑,000开头表示变量,但是null的所有位数全是0,所以被错误的判断为对象。使用Object.prototype.toString.call(xx)方法可以得正确的数据类型。

    Object.prototype.toString.call(null) // [object null]
    

    判断已知对象类型的方法: instanceof

    instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型,我们用一段伪代码来模拟其内部执行过程:

    instanceof (A,B) = {
        var L = A.__proto__;
        var R = B.prototype;
        if(L === R) {
            // A的内部属性 __proto__ 指向 B 的原型对象
            return true;
        }
        return false;
    }
    

    从上述过程可以看出,当 A 的 proto 指向 B 的 prototype 时,就认为 A 就是 B 的实例,我们再来看几个例子:

    [] instanceof Array; // true
    {} instanceof Object;// true
    new Date() instanceof Date;// true
     
    function Person(){};
    new Person() instanceof Person;
     
    [] instanceof Object; // true
    new Date() instanceof Object;// true
    new Person instanceof Object;// true
    

    从 instanceof 能够判断出 [ ].proto 指向 Array.prototype,而 Array.prototype.proto 又指向了Object.prototype,最终 Object.prototype.proto 指向了null,标志着原型链的结束。因此,[]、Array、Object 就在内部形成了一条原型链:

    image

    从原型链可以看出,[] 的 proto 直接指向Array.prototype,间接指向 Object.prototype,所以按照 instanceof 的判断规则,[] 就是Object的实例。依次类推,类似的 new Date()、new Person() 也会形成一条对应的原型链 。因此,instanceof 只能用来判断两个对象是否属于实例关系****, 而不能判断一个对象实例具体属于哪种类型。

    instanceof 操作符的问题在于,它假定只有一个全局执行环境。如果网页中包含多个框架,那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的构造函数。如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。

    constructor

    [].constructor = Array
    true.constructor = Boolean
    

    注意:

    1. null 和 undefined 是无效的对象,因此是不会有 constructor 存在的,这两种类型的数据需要通过其他方式来判断。

    2. 函数的 constructor 是不稳定的,这个主要体现在自定义对象上,当开发者重写 prototype 后,原有的 constructor 引用会丢失,constructor 会默认为 Object。

    Object.prototype.toString.call

    toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。

    相关文章

      网友评论

          本文标题:数据类型判断

          本文链接:https://www.haomeiwen.com/subject/frrgzftx.html