Skip to content

Commit

Permalink
Added support for ECMAScript 5 native bind method if available. Add…
Browse files Browse the repository at this point in the history
…itional unit test to cover multiple argument binds.
  • Loading branch information
AdamCraven committed Feb 20, 2011
1 parent 226b7d9 commit 9c9731e
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 4 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
6 changes: 4 additions & 2 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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); };
Expand Down Expand Up @@ -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)));
};
Expand Down

0 comments on commit 9c9731e

Please sign in to comment.