美文网首页
typeof与对象检测的碰撞

typeof与对象检测的碰撞

作者: BIGHAI | 来源:发表于2017-06-04 16:17 被阅读0次

    用npm安装superagent(版本号为3.5.2),在superagent包的lib文件夹下面有下面这两个文件:is-object和is-function;其中is-object文件如下:

    function isObject(obj) {
      return null !== obj && 'object' === typeof obj;
    }
    
    module.exports = isObject
    

    其中is-function文件如下:

    var isObject = require('./is-object');
    
    function isFunction(fn) {
      var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';
      return tag === '[object Function]';
    }
    
    module.exports = isFunction;
    

    很显然上面的那个isFunction函数是依赖isObject函数的,但是我们利用isObject来判断是否是一个对象又太草率了,关键代码就是下面这句:

    return null !== obj && 'object' === typeof obj;
    

    首先将null排除,因为typeof null === "object",接着在看利用typeof判断是否是对象。但是这样的做法太草率了,因为typeof返回的值等于object并不能够说明它是一个object。比如说,函数是对象吧,但是typeof对此返回的结果却是function。

    所以说上面的那个isFunction函数的写法是错误的。那下面来仔细了解一下typeof的用法:

    • typeof undefined:"undefined"
    • typeof null:"object"
    • typeof 1:"number"
    • typeof true:"boolean"
    • typeof "haha":"string"
    • typeof function(){}:"function"
    • typeof Symbol():"symbol"
    • typeof {}:"object"

    从上面的结果来看利用typeof来判断很可能所得到的结果和你所要求的是出乎意料的。

    END

    相关文章

      网友评论

          本文标题:typeof与对象检测的碰撞

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