From 72645ef225f9a98ff7c11600af080cd6e7671f8c Mon Sep 17 00:00:00 2001 From: Justin Ridgewell Date: Thu, 18 Jun 2015 11:38:45 -0400 Subject: [PATCH 1/2] Use Function#bind when available --- underscore.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/underscore.js b/underscore.js index c8d534b10..460f155b7 100644 --- a/underscore.js +++ b/underscore.js @@ -17,12 +17,13 @@ var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: - var ArrayProto = Array.prototype, ObjProto = Object.prototype; + var ArrayProto = Array.prototype, FuncProto = Function.prototype, ObjProto = Object.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, + bind = FuncProto.bind, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; @@ -712,7 +713,9 @@ // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. - _.bind = restArgs(function(func, context, args) { + _.bind = bind ? restArgs(function(func, args) { + return bind.apply(func, args); + }) : restArgs(function(func, context, args) { if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var bound = restArgs(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); From 2a11f8754aecb5481a62771f40c78a22fb757afe Mon Sep 17 00:00:00 2001 From: Julian Gonggrijp Date: Sun, 3 May 2020 04:14:57 +0200 Subject: [PATCH 2/2] Add a test to expose #2214 --- test/functions.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/functions.js b/test/functions.js index f037b996c..89bd0b119 100644 --- a/test/functions.js +++ b/test/functions.js @@ -46,6 +46,12 @@ assert.strictEqual(boundf().hello, 'moe curly', "When called without the new operator, it's OK to be bound to the context"); assert.ok(newBoundf instanceof F, 'a bound instance is an instance of the original function'); + // Ensure that we are not reproducing #2214. + var D = _.bind(Date, null, 2015, 5); + var newD = new D(10); + assert.ok(newD instanceof Date, 'works on variable argument constructors'); + assert.ok(newD.toISOString(), 'works on nontrivial constructors'); + assert.raises(function() { _.bind('notafunction'); }, TypeError, 'throws an error when binding to a non-function'); });