From e641c27759fa89a6430aaa92f85817f52b06557f Mon Sep 17 00:00:00 2001 From: Jay Phelps Date: Sun, 22 May 2016 17:42:49 -0700 Subject: [PATCH] Add support for function-bind operator e.g. func::bind(this) --- src/idempotent-bind.js | 10 ++++++++++ test/idempotent-bind-test.js | 13 +++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/idempotent-bind.js b/src/idempotent-bind.js index ac3b043..79c3261 100644 --- a/src/idempotent-bind.js +++ b/src/idempotent-bind.js @@ -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) { @@ -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."); } diff --git a/test/idempotent-bind-test.js b/test/idempotent-bind-test.js index 06be840..875023f 100644 --- a/test/idempotent-bind-test.js +++ b/test/idempotent-bind-test.js @@ -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 () { @@ -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)); + }); }); }); \ No newline at end of file