Ensure _.callback supports binding built-in methods. [closes #576]

This commit is contained in:
John-David Dalton
2014-06-09 01:40:02 -07:00
parent 9a152c23bb
commit d2edf11726
2 changed files with 16 additions and 14 deletions

View File

@@ -1355,8 +1355,7 @@
if (typeof func != 'function') { if (typeof func != 'function') {
return identity; return identity;
} }
// exit early for no `thisArg` or already bound by `Function#bind` if (typeof thisArg == 'undefined') {
if (typeof thisArg == 'undefined' || !('prototype' in func)) {
return func; return func;
} }
var data = func[expando]; var data = func[expando];
@@ -1372,7 +1371,7 @@
} }
if (!data) { if (!data) {
// checks if `func` references the `this` keyword and stores the result // checks if `func` references the `this` keyword and stores the result
data = reThis.test(source); data = reThis.test(source) || isNative(func);
setData(func, data); setData(func, data);
} }
} }
@@ -8117,7 +8116,7 @@
var type = typeof func, var type = typeof func,
isFunc = type == 'function'; isFunc = type == 'function';
if (isFunc && (typeof thisArg == 'undefined' || !('prototype' in func))) { if (isFunc && typeof thisArg == 'undefined') {
return func; return func;
} }
if (isFunc || func == null) { if (isFunc || func == null) {

View File

@@ -1741,16 +1741,16 @@
(function() { (function() {
test('should create a callback with a falsey `thisArg`', 1, function() { test('should create a callback with a falsey `thisArg`', 1, function() {
var values = _.map(falsey, function(value) { var expected = _.map(falsey, function(value) {
return Object(value == null ? root : value); return Object(value == null ? root : value);
}); });
var actual = _.map(values, function(value) { var actual = _.map(falsey, function(value) {
var callback = _.callback(function() { return this; }, value); var callback = _.callback(function() { return this; }, value);
return callback(); return callback();
}); });
deepEqual(actual, values); ok(_.isEqual(actual, expected));
}); });
test('should return `_.identity` when `func` is nullish', 2, function() { test('should return `_.identity` when `func` is nullish', 2, function() {
@@ -1818,15 +1818,18 @@
deepEqual(callback(2), expected); deepEqual(callback(2), expected);
}); });
test('should return the function provided if already bound with `Function#bind`', 1, function() { test('should support binding built-in methods', 2, function() {
function a() {} var object = { 'a': 1 },
callback = _.callback(Object.prototype.hasOwnProperty, object);
var object = {}, strictEqual(callback('a'), true);
bound = a.bind && a.bind(object);
if (bound && !('prototype' in bound)) { var fn = function () {},
var bound = a.bind(object); bound = fn.bind && fn.bind(object);
strictEqual(_.callback(bound, object), bound);
if (bound) {
callback = _.callback(bound, object);
notStrictEqual(callback, bound);
} }
else { else {
skipTest(); skipTest();