Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is typeof (/./) !== 'function' used in underscore

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?

like image 610
sissonb Avatar asked Jul 11 '13 17:07

sissonb


People also ask

What is the use of IS underscore array function?

Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays. Similar to without, but returns the values from array that are not present in the other arrays.

What does _ each do?

The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.

Is typeof a function?

The TypeOf function is an important tool when dealing with complex code. It allows a programmer to quickly check a variable's data type—or whether it's “undefined” or “null”—without going through the code line by line! Additionally, the TypeOf function can also check whether an operand is an object or not.

Is typeof a JavaScript function?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.


1 Answers

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 compatibility, as Underscore is, you may need to check for it.

like image 180
Jonathan Lonowski Avatar answered Oct 02 '22 20:10

Jonathan Lonowski