diff --git a/implementations/bind.js b/implementations/bind.js new file mode 100644 index 0000000..b32a15c --- /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, ...outerFuncArguments) { + const targetFunc = this; + + // return inner function + return function (...innerFuncArgs) { + + 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](...outerFuncArguments, ...innerFuncArgs); + delete someObj[propKey]; + return result; + }; +}; \ No newline at end of file