Skip to content

Commit

Permalink
Add support for function-bind operator e.g. func::bind(this)
Browse files Browse the repository at this point in the history
  • Loading branch information
jayphelps committed May 23, 2016
1 parent bb7c982 commit e641c27
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/idempotent-bind.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ function releaseBind(secondMap, thisArg) {
* @template T
*/
export function bind(target, thisArg) {
if (this !== undefined) {
target = this;
thisArg = target;
}

var secondMap = map.get(target);
// need to save the bound function into WeakMp.
if (thisArg == null) {
Expand All @@ -65,6 +70,11 @@ export function bind(target, thisArg) {
* @template T
*/
export function unbind(target, thisArg) {
if (this !== undefined) {
target = this;
thisArg = target;
}

if (typeof target !== "function") {
throw new Error("target must be function.");
}
Expand Down
13 changes: 13 additions & 0 deletions test/idempotent-bind-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ describe("idempotent-bind", function () {
};
assert(bind(f, null) === bind(f, null));
});

it("supports implicit `target` from callee's `this`", function () {
var f = function () {
};
assert(bind.call(f, this) === bind.call(f, this));
});
});
describe("#unbind", function () {
it("should release binding", function () {
Expand All @@ -41,5 +47,12 @@ describe("idempotent-bind", function () {
var g = bind(f, null);
assert(g === unbind(f, null));
});
it("should release binding for implicit `target`", function () {
var f = function () {
};
var g = bind.call(f, this);
unbind.call(f, this);
assert(g !== bind.call(f, this));
});
});
});

0 comments on commit e641c27

Please sign in to comment.