From bb250e7205b9e0b481233ae2bcf542d2e288dfd7 Mon Sep 17 00:00:00 2001 From: Mike Frawley Date: Mon, 22 Feb 2010 15:50:01 -0600 Subject: [PATCH] Much better strategy for calling native Array methods. Compare an object's function with === to the native version before calling it. That is, don't just assume that because an object has a 'filter' property thats a function, that we should call that in _.filter(). Expose the native methods found as _.native On the way towards being able to turn off native implementations, though there are tradeoffs... --- underscore.js | 43 +++++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/underscore.js b/underscore.js index bd74fbcf5..a445cdcb0 100644 --- a/underscore.js +++ b/underscore.js @@ -37,6 +37,25 @@ hasOwnProperty = Object.prototype.hasOwnProperty, propertyIsEnumerable = Object.prototype.propertyIsEnumerable; + // All native implementations we hope to use are declared here, + // mostly Array.prototype methods. + // + // 'native' is on the long list of reserved words. + // Ok to use as a property name, though jsLint doesn't agree. + var Native = _['native'] = { + forEach: Array.prototype.forEach, + map: Array.prototype.map, + reduce: Array.prototype.reduce, + reduceRight: Array.prototype.reduceRight, + filter: Array.prototype.filter, + every: Array.prototype.every, + some: Array.prototype.some, + indexOf: Array.prototype.indexOf, + lastIndexOf: Array.prototype.lastIndexOf, + isArray: Array.isArray, + keys: Object.keys + }; + // Current version. _.VERSION = '0.5.8'; @@ -49,7 +68,7 @@ _.forEach = function(obj, iterator, context) { var index = 0; try { - if (obj.forEach) { + if (obj.forEach === Native.forEach) { obj.forEach(iterator, context); } else if (_.isNumber(obj.length)) { for (var i=0, l=obj.length; i