From 6848c40a3dcc0fc55cca3dbf9337f0fd7d9bc039 Mon Sep 17 00:00:00 2001 From: Ashish Date: Sat, 12 Oct 2019 21:38:45 +0530 Subject: [PATCH 1/2] issue#25 - Implement Function.prototype.bind() --- implementations/bind.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 implementations/bind.js diff --git a/implementations/bind.js b/implementations/bind.js new file mode 100644 index 0000000..25df2b8 --- /dev/null +++ b/implementations/bind.js @@ -0,0 +1,27 @@ + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind + +/* + Bind function returns a new bounded function and passes the "this" reference to be used by the targeted function + The bind() function creates a new bound function, which is an exotic function object + that wraps the original function object. +*/ + +Function.prototype.altBind = function (someObj, ...outerFuncArguments1) { + const targetFunc = this; + + // return inner function + return function (...innerFuncArgs1) { + + let propKey = Math.random().toString(); + while (someObj.hasOwnProperty(propKey)) { + propKey = Math.random().toString(); + } + someObj[propKey] = targetFunc; + + // prepend outer args to inner args + const result = someObj[propKey](...outerFuncArguments1, ...innerFuncArgs1); + delete someObj[propKey]; + return result; + } +} \ No newline at end of file From d8914f59f6f77e673c83efb0c59b4c5e0ce9767a Mon Sep 17 00:00:00 2001 From: Ashish Date: Sat, 12 Oct 2019 22:17:28 +0530 Subject: [PATCH 2/2] issue#25 - Implement Function.prototype.bind() --- implementations/bind.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/implementations/bind.js b/implementations/bind.js index 25df2b8..b32a15c 100644 --- a/implementations/bind.js +++ b/implementations/bind.js @@ -7,11 +7,11 @@ that wraps the original function object. */ -Function.prototype.altBind = function (someObj, ...outerFuncArguments1) { +Function.prototype.altBind = function (someObj, ...outerFuncArguments) { const targetFunc = this; // return inner function - return function (...innerFuncArgs1) { + return function (...innerFuncArgs) { let propKey = Math.random().toString(); while (someObj.hasOwnProperty(propKey)) { @@ -20,8 +20,8 @@ Function.prototype.altBind = function (someObj, ...outerFuncArguments1) { someObj[propKey] = targetFunc; // prepend outer args to inner args - const result = someObj[propKey](...outerFuncArguments1, ...innerFuncArgs1); + const result = someObj[propKey](...outerFuncArguments, ...innerFuncArgs); delete someObj[propKey]; return result; - } -} \ No newline at end of file + }; +}; \ No newline at end of file