自己封装一个获取数据类型的方法

225 阅读1分钟

自己封装一个获取数据类型的方法

JS中获取数据类型的方法:

  • typeof 只能检测简单数据类型 ,且typeof null 是object
  • xxx instanceof xxx2
  • xxx.construtor
  • Object.prototype.toString.call(检测的数据) = '[object 数据类型]' 这种方法是最准确的

instanceof

xxx instanceof xxx2 :看xxx到基类的原型链上 有没有 xxx2的身影,有结果就是true 没有就是false 所有引用数据类型数据 instanceof Object 都是true 所有值类型数据 instanceof 任意 结果都是false

/* temp通过__proto__向上查找的时候 若有某次的temp._proto_=== classN.prototype 则返回true;没有就继续往上边查,若有某次的temp._proto_ ===null,则返回false */

function myInstance(temp, classN) {
        let str = typeof temp;
        //temp不是对象也不是函数证明它是值类型 返回false
        if (str !== 'object' && str !== 'function') return false;
        let left = temp.__proto__,
            right = classN.prototype;
        while (left) {
            if (left === right) return true;
            left = temp.__proto__;
        }
        return false;
    }
 function instance_of(L, R) {
        //L 表示左表达式,R 表示右表达式
        var O = R.prototype; // 取 R 的显示原型
        L = L.__proto__; // 取 L 的隐式原型
        while (true) {
            if (L === null) return false;
            if (O === L)
                // 这里重点:当 O 严格等于 L 时,返回 true
                return true;
            L = L.__proto__;
        }
    }
	[]  instanceof  Array; // true 
    []  instanceof  Object;// true
    []  instanceof  Number; // false
    1   instanceof  Number; // false

    myInstance([],Number) // false

自己分装的getType函数获取数据类型

 Object.prototype.getType = function(){
        // Object.prototypetoString.call()
        let str = ({}).toString.call(this);// '[object Number]'
        let reg = /[a-z]+/ig;
        reg.test(str);
        return reg.exec(str)[0].toLowerCase()
    } 
     Object.prototype.getType = function(){
        let str = ({}).toString.call(this);// '[object Number]'
        let reg = /.{8}(\w+)/;
        return reg.exec(str)[1].toLowerCase()
    } 

    Object.prototype.getType = function(){
        let str = ({}).toString.call(this);// '[object Number]'
        // let reg = /(\w+)\]$/; // Number]  Number
        let reg = / (\w+)/;// ' Number'  'Number'
        return reg.exec(str)[1].toLowerCase()
    }
    ''.getType();// string
    [].getType();// array