30秒学会 JavaScript 片段 · 2023年11月12日

30秒学会 JavaScript 片段 – Bind all object methods

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.

代码实现

const bindAll = (obj, ...fns) =>
  fns.forEach(
    fn => (
      (f = obj[fn]),
      (obj[fn] = function() {
        return f.apply(obj);
      })
    )
  );

let view = {
  label: 'docs',
  click: function() {
    console.log('clicked ' + this.label);
  }
};
bindAll(view, 'click');
document.body.addEventListener('click', view.click);
// Log 'clicked docs' when clicked.

翻译自:https://www.30secondsofcode.org/js/s/bind-object-methods