Skip to content

Commit

Permalink
Ensure a bound instance is an instance of the bound and original func…
Browse files Browse the repository at this point in the history
…tion.
  • Loading branch information
jdalton committed Dec 1, 2012
1 parent b1f266f commit 6a6de57
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
4 changes: 3 additions & 1 deletion test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ $(document).ready(function() {
// To test this with a modern browser, set underscore's nativeBind to undefined
var F = function () { return this; };
var Boundf = _.bind(F, {hello: "moe curly"});
equal(new Boundf().hello, undefined, "function should not be bound to the context, to comply with ECMAScript 5");
var newBoundf = new Boundf();
equal(newBoundf.hello, undefined, "function should not be bound to the context, to comply with ECMAScript 5");
equal(Boundf().hello, "moe curly", "When called without the new operator, it's OK to be bound to the context");
ok(newBoundf instanceof Boundf && newBoundf instanceof F, "a bound instance is an instance of the bound and original function");
});

test("bindAll", function() {
Expand Down
17 changes: 10 additions & 7 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -573,18 +573,21 @@
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
var args = slice.call(arguments, 2);
var bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
var result = func.apply(this, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
return this;
};
if (func && func.prototype) {
ctor.prototype = func.prototype;
bound.prototype = new ctor;
ctor.prototype = null;
}
return bound;
};

// Bind all of an object's methods to that object. Useful for ensuring that
Expand Down

0 comments on commit 6a6de57

Please sign in to comment.