Skip to content

Commit 6848c40

Browse files
issue#25 - Implement Function.prototype.bind()
1 parent 8508aba commit 6848c40

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

implementations/bind.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
3+
4+
/*
5+
Bind function returns a new bounded function and passes the "this" reference to be used by the targeted function
6+
The bind() function creates a new bound function, which is an exotic function object
7+
that wraps the original function object.
8+
*/
9+
10+
Function.prototype.altBind = function (someObj, ...outerFuncArguments1) {
11+
const targetFunc = this;
12+
13+
// return inner function
14+
return function (...innerFuncArgs1) {
15+
16+
let propKey = Math.random().toString();
17+
while (someObj.hasOwnProperty(propKey)) {
18+
propKey = Math.random().toString();
19+
}
20+
someObj[propKey] = targetFunc;
21+
22+
// prepend outer args to inner args
23+
const result = someObj[propKey](...outerFuncArguments1, ...innerFuncArgs1);
24+
delete someObj[propKey];
25+
return result;
26+
}
27+
}

0 commit comments

Comments
 (0)