为什么UnderscoreJS使用toString.call()而不是typeof?

时间:2012-05-01 07:42:06

标签: javascript underscore.js

在UnderscoreJS的引擎盖下,我看到了:

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

  _.isString = function(obj) {
    return toString.call(obj) == '[object String]';
  };

  _.isNumber = function(obj) {
    return toString.call(obj) == '[object Number]';
  };

这似乎是一个奇怪的选择。为什么不使用typeof来确定值是字符串,函数还是数字?使用toString是否有性能提升?旧浏览器不支持typeof吗?

2 个答案:

答案 0 :(得分:13)

实际上这是因为通过[[Class]]检查来检查toString会更快。也可以减少错误,因为toString为您提供了精确的类......

检查一下:

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

你可以在这里看到下划线typeof vs toString的基准:

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

还有一些github问题有更好的解释:

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

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

编辑1:

您还可以查看这篇精彩的文章:

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

答案 1 :(得分:2)

Drinchev的回答是部分正确的。在大多数浏览器中,toString目前比使用typeOf慢。使用typeOf的See the 7th revision of the test he posted。两者仍然非常快,但在大多数情况下,这种性能差异不会引人注意,并且权衡价值比鸭子打字/ typeOf更符合规格。

Underscore pull request 321(列出了drinchev)深入讨论了权衡以及他们决定使用toString的原因。