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

后端 未结 2 527
清歌不尽
清歌不尽 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:52

    drinchev's answer is partially correct. toString is currently much slower than using typeOf in most browsers. See the 7th revision of the test he posted which uses typeOf. Both are still very fast though so in most cases this performance difference won't be noticeable and the tradeoff is worth conforming to the specs better than duck typing / typeOf.

    Underscore pull request 321 (that drinchev listed) has an in-depth discussion of the tradeoffs and why they decided to use toString.

提交回复
热议问题