JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – 为什么UnderscoreJS使用toString.call()而不是typeof?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
看看在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有性能增益吗?旧版浏览器不支持类型?

解决方法

实际上这是因通过使用toString检查来检查[[Class]]是更快的.也可以有更少的错误,因为toString给你确切的类…

检查:

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

您可以在这里看到下划线类型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/

大佬总结

以上是大佬教程为你收集整理的javascript – 为什么UnderscoreJS使用toString.call()而不是typeof?全部内容,希望文章能够帮你解决javascript – 为什么UnderscoreJS使用toString.call()而不是typeof?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。