From 9c9731e08e3876afae912bf09acf816430fdeb39 Mon Sep 17 00:00:00 2001 From: Adam Craven Date: Sun, 20 Feb 2011 21:03:52 +0100 Subject: [PATCH] Added support for ECMAScript 5 native `bind` method if available. Additional unit test to cover multiple argument binds. --- test/functions.js | 4 ++++ underscore.js | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/test/functions.js b/test/functions.js index 230ebea9a..f74bc7294 100644 --- a/test/functions.js +++ b/test/functions.js @@ -20,6 +20,10 @@ $(document).ready(function() { var func = _.bind(func, this, 'curly'); equals(func(), 'hello: curly', 'the function was completely applied in advance'); + + var func = function(salutation, firstname, lastname) { return salutation + ': ' + firstname + ' ' + lastname }; + func = _.bind(func, this, 'hello', 'moe', 'curly'); + equals(func(), 'hello: moe curly', 'the function was partially applied in advance and can accept multiple arguments'); }); test("functions: bindAll", function() { diff --git a/underscore.js b/underscore.js index 5aaaca372..854175858 100644 --- a/underscore.js +++ b/underscore.js @@ -21,7 +21,7 @@ var breaker = {}; // Save bytes in the minified (but not gzipped) version: - var ArrayProto = Array.prototype, ObjProto = Object.prototype; + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var slice = ArrayProto.slice, @@ -42,7 +42,8 @@ nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, - nativeKeys = Object.keys; + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { return new wrapper(obj); }; @@ -408,6 +409,7 @@ // optionally). Binding with arguments is also known as `curry`. _.bind = function(func, obj) { var args = slice.call(arguments, 2); + if(nativeBind && func.bind === nativeBind) return FuncProto.bind.apply(func, slice.call(arguments, 1)); return function() { return func.apply(obj || {}, args.concat(slice.call(arguments))); };