Skip to content
This repository has been archived by the owner on Sep 10, 2024. It is now read-only.

convoyinc/protobind

Repository files navigation

protobind

Binds all methods on an object to itself, including those defined on its prototype, and inherited up the chain. Also ensures that any methods' properties are preserved.

import autobind from 'protobind';

class Foo {
  constructor() {
    autobind(this);
  }

  foo() {
    return 'stuff';
  }

  bar() {
    return this.foo();
  }
}

const bar = new Foo().bar;
bar(); // 'stuff'

You can also use it as a decorator:

import autobind from 'protobind';

@autobind
class Foo {
  foo() {
    return 'stuff';
  }

  bar() {
    return this.foo();
  }
}

const bar = new Foo().bar;
bar(); // 'stuff'