Last active
June 25, 2018 02:21
-
-
Save Falieson/580e4feb26e92ece7d93b102c78a6f76 to your computer and use it in GitHub Desktop.
js impl of bind
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tslint:disable no-any | |
export default function bind2(this: any, that: any) { | |
const f = this // tslint:disable-line no-this-assignment | |
const initialArgs = Array.prototype.slice.call(arguments, 1) | |
return (finalArgs: any[]) => f.apply(that, [...initialArgs, ...finalArgs]) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tslint:disable no-any | |
import bind2 from '../bind2' | |
function decorate(obj: any): any { | |
const res = new Function() | |
Object.assign(res, obj) | |
res['bind2'] = bind2 // tslint:disable-line no-string-literal | |
return res | |
} | |
describe('.bind2(target)', () => { | |
test('works', () => { | |
const data = { | |
getX() { | |
return this.x | |
}, | |
x: 42, | |
} | |
const unboundGetX = data.getX | |
const boundGetX = decorate(unboundGetX).bind2(data) | |
expect(boundGetX()).toEqual(42) | |
}) | |
}) |
Author
Falieson
commented
Jun 25, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment