最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why is typeof (.) !== 'function' used in underscore - Stack Overflow

programmeradmin2浏览0评论

I was reading through the source for the _.isFunction() function and saw this line:

if (typeof (/./) !== 'function') {

and I don't understand why it's there. /./ is a regex that always seem to have the type object. Why wouldn't _.isFunction be redefined if /./ type was a function?

I was reading through the source for the _.isFunction() function and saw this line:

if (typeof (/./) !== 'function') {

and I don't understand why it's there. /./ is a regex that always seem to have the type object. Why wouldn't _.isFunction be redefined if /./ type was a function?

Share Improve this question edited Jul 13, 2013 at 17:28 acdcjunior 136k37 gold badges338 silver badges310 bronze badges asked Jul 11, 2013 at 17:45 sissonbsissonb 3,7804 gold badges30 silver badges56 bronze badges 3
  • 4 Answered here: stackoverflow./questions/5054352/… – Dogbert Commented Jul 11, 2013 at 17:49
  • Ah, so the check is to avoid accidentally having regex considered function? Nice. Excellent question. – ZenMaster Commented Jul 11, 2013 at 17:52
  • 3 "Why wouldn't _.isFunction be defined" - it's being redefined. The original toString() definition is two blocks up. – Rup Commented Jul 11, 2013 at 17:52
Add a ment  | 

1 Answer 1

Reset to default 16

Some versions of various JavaScript engines have allowed for calling RegExp as another way of using .exec():

var pattern = /./;

pattern('abc');
pattern.exec('abc');

And, since they were Callable, typeof considered them functions:

Type of val: Object (native or host and does implement [[Call]])
Result: "function"

To my knowledge, though, current versions don't exhibit this behavior and will throw a TypeError. But, if you're concerned with backwards patibility, as Underscore is, you may need to check for it.

发布评论

评论列表(0)

  1. 暂无评论