为什么UnderscoreJS使用toString.call()而不是typeof? [英] Why does UnderscoreJS use toString.call() instead of typeof?
问题描述
在UnderscoreJS的引擎盖下,我看到:
Looking under the hood in UnderscoreJS, I see:
_.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吗?
This seems like an odd choice. Why not just use typeof to determine whether a value is a string, function, or number? Is there a performance gain by using toString? Is typeof not supported by older browsers?
推荐答案
实际上这是因为检查更快[[Class]]
通过 toString
进行检查。也可以减少错误,因为toString为您提供了精确的类......
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 ...
检查:
var fn = function() {
console.log(typeof(arguments)) // returns object
console.log(arguments.toString()) // returns object Arguments
}
你可以在这里看到下划线typeof vs toString的基准:
You could see the benchmark for underscore typeof vs toString here :
http://jsperf.com/underscore- js-istype-alternatives
还有一些github问题有更好的解释:
Also there are some github issues with better explaination :
< a href =https://github.com/documentcloud/underscore/pull/332\"rel =noreferrer> https://github.com/documentcloud/underscore/pull/332
https://github.com/documentcloud/underscore/pull / 321
编辑1:
你可以als o查看这篇好文章:
You could also check this great article :
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
这篇关于为什么UnderscoreJS使用toString.call()而不是typeof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!