War*_*tto 10 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]';
};
Run Code Online (Sandbox Code Playgroud)
这似乎是一个奇怪的选择.为什么不使用typeof来确定值是字符串,函数还是数字?使用toString是否有性能提升?旧浏览器不支持typeof吗?
dri*_*hev 13
实际上这是因为[[Class]]通过检查检查更快toString.也可以减少错误,因为toString为您提供了精确的类......
检查一下:
var fn = function() {
console.log(typeof(arguments)) // returns object
console.log(arguments.toString()) // returns object Arguments
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到下划线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/
| 归档时间: |
|
| 查看次数: |
2184 次 |
| 最近记录: |