Why does UnderscoreJS use toString.call() instead of typeof?

后端 未结 2 578
清歌不尽
清歌不尽 2021-02-06 00:33

Looking under the hood in UnderscoreJS, I see:

  _.isFunction = function(obj) {
    return toString.call(obj) == \'[object Function]\';
  };

  _.isString = func         


        
2条回答
  •  我寻月下人不归
    2021-02-06 00:58

    Well actually this is because it is faster to check the [[Class]] by checking with toString. Also there could be less mistakes, since toString gives you the exact Class ...

    check this :

    var fn = function() { 
        console.log(typeof(arguments)) // returns object
        console.log(arguments.toString()) // returns object Arguments
    }
    

    You could see the benchmark for underscore typeof vs toString here :

    http://jsperf.com/underscore-js-istype-alternatives

    Also there are some github issues with better explaination :

    https://github.com/documentcloud/underscore/pull/332

    https://github.com/documentcloud/underscore/pull/321

    EDIT 1 :

    You could also check this great article :

    http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

提交回复
热议问题