How does .isNumber work in underscore.js?

In underscore.js, the following code seems to add _.isNumber ()

// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); 

but something else needs to happen because copying this code directly into firefox makes it fail, because toString.call(5) returns [xpconnect wrapped native prototype] - so it obviously does something else somewhere - but I I can not understand that.

Here is an example of the results in firefox:

http://jsbin.com/uviyaz/2/edit

+4
source share
2 answers

In your jsbin, window.toString is displayed, where when the underscore uses Object.prototype.toString , they flatten it to toString locally in their code.

See http://jsbin.com/uviyaz/3/edit

See also the underline source where they do it:

  // Create quick reference variables for speed access to core prototypes. var slice = ArrayProto.slice, unshift = ArrayProto.unshift, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; 
+4
source

In underscores, toString is a local variable whose value is Object.prototype.toString . You suggested that this is a global function - why you got unexpected results.

From underline the source code :

  // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, unshift = ArrayProto.unshift, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; 
0
source

All Articles