-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathbind.js
27 lines (21 loc) · 867 Bytes
/
bind.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
};
};