Skip to content

Latest commit

 

History

History
74 lines (64 loc) · 1.82 KB

bindAll.md

File metadata and controls

74 lines (64 loc) · 1.82 KB
title tags author_title author_url author_image_url description image
bindAll
object,function,intermediate
Deepak Vishwakarma
Implementation of "bindAll" in typescript, javascript and deno.

TS JS Deno

Binds methods of an object to the object itself, overwriting the existing method.

Use Array.prototype.forEach() to return a function that uses Function.prototype.apply() to apply the given context (obj) to fn for each function specified.

export const bindAll = (obj: any, ...fns: string[]) =>
  fns.forEach((key: string) => {
    if (typeof obj[key] === "function") {
      const f = obj[key];
      obj[key] = function (...args: any[]) {
        return f.apply(obj, args);
      };
    }
  });
class User {
  #name = "Test";
  getName() {
    return this.#name;
  }
}
const user = new User();
bindAll(user, "getName");

const getName = user.getName;
assertEquals(getName(), "Test");

// JS
var view = {
  label: "docs",
  click: function () {
    console.log("clicked " + this.label);
  },
};
bindAll(view, "click");
jQuery(element).on("click", view.click); // Logs 'clicked docs' when clicked.

React:

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    bindAll(this, "handleClick", "handleMove");
  }

  handleClick() {
    // code
  }
  handleMove() {
    // code
  }
  render() {
    // code
  }
}