Nest all content into snippets

This commit is contained in:
Angelos Chalaris
2023-05-07 16:07:29 +03:00
parent 2ecadbada9
commit 6a45d2ec07
1240 changed files with 0 additions and 0 deletions

27
snippets/js/s/bind.md Normal file
View File

@ -0,0 +1,27 @@
---
title: Bind function context
type: snippet
language: javascript
tags: [function,object]
cover: tranquility
dateModified: 2020-10-18T23:04:45+03:00
---
Creates a function that invokes `fn` with a given context, optionally prepending any additional supplied parameters to the arguments.
- Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.
- Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.
```js
const bind = (fn, context, ...boundArgs) => (...args) =>
fn.apply(context, [...boundArgs, ...args]);
```
```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!'
```