为什么UnderscoreJS使用toString.call()而不是typeof
Why does UnderscoreJS use toString.call() instead of 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 是否有性能提升?旧版浏览器不支持 typeof 吗?
通过检查toString
来检查[[Class]]
更快。此外,错误可能会更少,因为 toString 为您提供了确切的类......
检查这个 :
var fn = function() {
console.log(typeof(arguments)) // returns object
console.log(arguments.toString()) // returns object Arguments
}
您可以在此处查看下划线类型与 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/
Drinchev的回答部分正确。 toString 目前比在大多数浏览器中使用 typeOf 慢得多。请参阅他发布的测试的第 7 次修订版,该版本使用 typeOf。两者都仍然非常快,因此在大多数情况下,这种性能差异不会很明显,并且权衡值得比鸭子类型/typeOf更好地符合规格。
下划线拉取请求 321(drinchev 列出的)深入讨论了权衡以及他们决定使用 toString 的原因。
- 在underscorejs模板中使用闭包
- 为什么typeof的数组的数组的未定义值返回为“0”;未定义的“;我的条件不认为是真的
- (typeof variable === “function”) 和 jQuery.isFunction() 有什么区别
- 打印到控制台时为NaN,但typeof为数字jquery
- 避免使用underscorejs上的全局变量
- 函数的typeof调用,该函数的名称以字符串形式传递
- typeof new Function()总是“;函数”;
- 为什么使用 Object('123') 创建对象会创建一个 String() 对象,但 typeof 是“对象”
- Javascript 混淆了 null、instanceof 和 typeof 的语法不一致
- 使JS对象从typeof=“object”变为typeof=“undefined”
- javascript中的typeof()函数错误
- typeof关键字的行为
- understanding Javascript Typeof
- 比较underscorejs中的两个对象数组
- 为什么typeof(null)返回“;对象”;,但是你可以't为其分配属性
- 是否有必要在每个“typeof”之后调用“toLowerCase()”
- 如何使用underscorejs获取嵌套对象的内部数组
- JavaScript - typeof Object vs Object()
- 得到一个“无法读取未定义的属性'myVar'”,即使使用 typeof 也无法解决
- 为什么UnderscoreJS使用toString.call()而不是typeof