Files
30-seconds-of-code/snippets/js/s/bind-object-method.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

31 lines
976 B
Markdown

---
title: Bind object method
type: snippet
language: javascript
tags: [function,object]
cover: oven-paddle
excerpt: Creates a function that invokes a method at a key in an object, with optional additional parameters.
dateModified: 2020-10-18T23:04:45+03:00
---
Creates a function that invokes the method at a given key of an object, optionally prepending any additional supplied parameters to the arguments.
- Return a `function` that uses `Function.prototype.apply()` to bind `context[fn]` to `context`.
- Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.
```js
const bindKey = (context, fn, ...boundArgs) => (...args) =>
context[fn].apply(context, [...boundArgs, ...args]);
```
```js
const freddy = {
user: 'fred',
greet: function(greeting, punctuation) {
return greeting + ' ' + this.user + punctuation;
}
};
const freddyBound = bindKey(freddy, 'greet');
console.log(freddyBound('hi', '!')); // 'hi fred!'
```