From cc8b6ba809782e07ca7345342a3a4254cf73bceb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 24 Jan 2018 14:14:49 +0200 Subject: [PATCH] Add bind --- snippets/bind.md | 22 ++++++++++++++++++++++ tag_database | 1 + 2 files changed, 23 insertions(+) create mode 100644 snippets/bind.md diff --git a/snippets/bind.md b/snippets/bind.md new file mode 100644 index 000000000..73e1ab253 --- /dev/null +++ b/snippets/bind.md @@ -0,0 +1,22 @@ +### bind + +Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments. + +Return a `function` that uses `Function.apply()` to apply the given `context` to `fn`. +Use `Array.concat()` to prepend any additional supplied parameters to the arguments. + +```js +const bind = (fn, context, ...args) => + function() { + return fn.apply(context, args.concat(...arguments)); + }; +``` + +```js +function greet(greeting, punctuation) { + return greeting + ' ' + this.user + punctuation; +} +const freddy = { 'user': 'fred' }; +const freddyBound = bind(greet, freddy); +console.log(freddyBound('hi','!')); // 'hi fred!' +``` diff --git a/tag_database b/tag_database index 3fd6e374f..fd216c710 100644 --- a/tag_database +++ b/tag_database @@ -4,6 +4,7 @@ ary:adapter,function atob:node,string,utility average:math,array averageBy:math,array,function +bind:function,object bottomVisible:browser btoa:node,string,utility byteSize:string