Rename js snippets
This commit is contained in:
37
snippets/js/s/bind-object-methods.md
Normal file
37
snippets/js/s/bind-object-methods.md
Normal file
@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Bind all object methods
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [object,function]
|
||||
cover: laptop-with-code
|
||||
dateModified: 2020-11-03T22:11:18+02:00
|
||||
---
|
||||
|
||||
Binds methods of an object to the object itself, overwriting the existing method.
|
||||
|
||||
- Use `Array.prototype.forEach()` to iterate over the given `fns`.
|
||||
- Return a function for each one, using `Function.prototype.apply()` to apply the given context (`obj`) to `fn`.
|
||||
|
||||
```js
|
||||
const bindAll = (obj, ...fns) =>
|
||||
fns.forEach(
|
||||
fn => (
|
||||
(f = obj[fn]),
|
||||
(obj[fn] = function() {
|
||||
return f.apply(obj);
|
||||
})
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
var view = {
|
||||
label: 'docs',
|
||||
click: function() {
|
||||
console.log('clicked ' + this.label);
|
||||
}
|
||||
};
|
||||
bindAll(view, 'click');
|
||||
document.body.addEventListener('click', view.click);
|
||||
// Log 'clicked docs' when clicked.
|
||||
```
|
||||
Reference in New Issue
Block a user