_.isFunction(a)与==='function'的类型? JavaScript的

时间:2013-06-14 12:06:18

标签: javascript performance underscore.js typeof

我认为这可能只是性能问题 - http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/2

似乎typeof更快..所以我的问题是 - 哪个更适合使用?

2 个答案:

答案 0 :(得分:95)

没有理由不使用typeof

不仅速度更快,而且ECMAScript specification确保所有函数都具有“函数”类型,并且只有函数可以具有“函数”类型:

enter image description here

此运算符专门用于获取值的类型,为什么不使用它呢?

答案 1 :(得分:12)

首先,Underscore不再使用该实现了。它优化为typeof,除非typeof /./返回function,因为它至少在older versions of Chrome

您可以在源代码中找到它:http://underscorejs.org/underscore.js

// Optimize `isFunction` if appropriate.
  if (typeof (/./) !== 'function') {
    _.isFunction = function(obj) {
      return typeof obj === 'function';
    };
  }

新jsperf:http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/3

它仍然在FF中显示出相当大的性能(但比你在问题中发布的天真实现要少得多),这是由于函数调用的开销与内联代码相比。

相关问题