├── .editorconfig ├── .gitattributes ├── .github ├── funding.yml ├── security.md └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── react.d.ts ├── react.js ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/funding.yml: -------------------------------------------------------------------------------- 1 | github: sindresorhus 2 | open_collective: sindresorhus 3 | tidelift: npm/auto-bind 4 | custom: https://sindresorhus.com/donate 5 | -------------------------------------------------------------------------------- /.github/security.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. 4 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 16 14 | steps: 15 | - uses: actions/checkout@v2 16 | - uses: actions/setup-node@v2 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - run: npm install 20 | - run: npm test 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export interface Options { 2 | /** 3 | Bind only the given methods. 4 | */ 5 | readonly include?: ReadonlyArray; 6 | 7 | /** 8 | Bind methods except for the given methods. 9 | */ 10 | readonly exclude?: ReadonlyArray; 11 | } 12 | 13 | /** 14 | Automatically bind methods to their class instance. 15 | 16 | @param self - An object with methods to bind. 17 | 18 | @example 19 | ``` 20 | import autoBind from 'auto-bind'; 21 | 22 | class Unicorn { 23 | constructor(name) { 24 | this.name = name; 25 | autoBind(this); 26 | } 27 | 28 | message() { 29 | return `${this.name} is awesome!`; 30 | } 31 | } 32 | 33 | const unicorn = new Unicorn('Rainbow'); 34 | 35 | // Grab the method off the class instance 36 | const message = unicorn.message; 37 | 38 | // Still bound to the class instance 39 | message(); 40 | //=> 'Rainbow is awesome!' 41 | 42 | // Without `autoBind(this)`, the above would have resulted in 43 | message(); 44 | //=> Error: Cannot read property 'name' of undefined 45 | ``` 46 | */ 47 | export default function autoBind>( // This has to use `any` to be compatible with classes. 48 | self: SelfType, 49 | options?: Options 50 | ): SelfType; 51 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | // Gets all non-builtin properties up the prototype chain. 2 | const getAllProperties = object => { 3 | const properties = new Set(); 4 | 5 | do { 6 | for (const key of Reflect.ownKeys(object)) { 7 | properties.add([object, key]); 8 | } 9 | } while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype); 10 | 11 | return properties; 12 | }; 13 | 14 | export default function autoBind(self, {include, exclude} = {}) { 15 | const filter = key => { 16 | const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); 17 | 18 | if (include) { 19 | return include.some(match); // eslint-disable-line unicorn/no-array-callback-reference 20 | } 21 | 22 | if (exclude) { 23 | return !exclude.some(match); // eslint-disable-line unicorn/no-array-callback-reference 24 | } 25 | 26 | return true; 27 | }; 28 | 29 | for (const [object, key] of getAllProperties(self.constructor.prototype)) { 30 | if (key === 'constructor' || !filter(key)) { 31 | continue; 32 | } 33 | 34 | const descriptor = Reflect.getOwnPropertyDescriptor(object, key); 35 | if (descriptor && typeof descriptor.value === 'function') { 36 | self[key] = self[key].bind(self); 37 | } 38 | } 39 | 40 | return self; 41 | } 42 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import {Component as ReactComponent} from 'react'; 3 | import autoBindReact from './react.js'; 4 | import autoBind from './index.js'; 5 | 6 | const foo = { 7 | bar: 'bar', 8 | 9 | method(_foo: string) { 10 | return this.bar; 11 | }, 12 | }; 13 | 14 | expectType(autoBind(foo)); 15 | expectType(autoBind(foo, {include: ['foo', /bar/]})); 16 | expectType(autoBind(foo, {exclude: ['foo', /bar/]})); 17 | 18 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class, @typescript-eslint/no-unused-vars 19 | class Foo { 20 | constructor() { 21 | autoBind(this); 22 | } 23 | } 24 | 25 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 26 | class Bar extends ReactComponent { 27 | constructor(props: Record) { 28 | super(props); 29 | 30 | expectType(autoBindReact(this)); 31 | expectType(autoBindReact(this, {include: ['foo', /bar/]})); 32 | expectType(autoBindReact(this, {exclude: ['foo', /bar/]})); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auto-bind", 3 | "version": "5.0.1", 4 | "description": "Automatically bind methods to their class instance", 5 | "license": "MIT", 6 | "repository": "sindresorhus/auto-bind", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | ".": "./index.js", 16 | "./react": "./react.js" 17 | }, 18 | "engines": { 19 | "node": "^12.20.0 || ^14.13.1 || >=16.0.0" 20 | }, 21 | "scripts": { 22 | "test": "xo && ava && tsd" 23 | }, 24 | "files": [ 25 | "index.js", 26 | "index.d.ts", 27 | "react.js", 28 | "react.d.ts" 29 | ], 30 | "keywords": [ 31 | "auto", 32 | "bind", 33 | "class", 34 | "methods", 35 | "method", 36 | "automatically", 37 | "prototype", 38 | "instance", 39 | "function", 40 | "this", 41 | "self", 42 | "react", 43 | "component" 44 | ], 45 | "devDependencies": { 46 | "@types/react": "^17.0.29", 47 | "ava": "^3.15.0", 48 | "tsd": "^0.18.0", 49 | "xo": "^0.45.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /react.d.ts: -------------------------------------------------------------------------------- 1 | import {Component as ReactComponent} from 'react'; 2 | import autoBind, {Options} from './index.js'; 3 | 4 | /** 5 | Same as `autoBind` but excludes the default [React component methods](https://reactjs.org/docs/react-component.html). 6 | 7 | @param self - An object with methods to bind. 8 | 9 | @example 10 | ``` 11 | import autoBindReact from 'auto-bind/react'; 12 | 13 | class Foo extends React.Component { 14 | constructor(props) { 15 | super(props); 16 | autoBindReact(this); 17 | } 18 | 19 | // … 20 | } 21 | ``` 22 | */ 23 | export default function autoBindReact( 24 | self: SelfType, 25 | options?: Options 26 | ): SelfType; 27 | -------------------------------------------------------------------------------- /react.js: -------------------------------------------------------------------------------- 1 | import autoBind from './index.js'; 2 | 3 | const excludedReactMethods = [ 4 | 'componentWillMount', 5 | 'UNSAFE_componentWillMount', 6 | 'render', 7 | 'getSnapshotBeforeUpdate', 8 | 'componentDidMount', 9 | 'componentWillReceiveProps', 10 | 'UNSAFE_componentWillReceiveProps', 11 | 'shouldComponentUpdate', 12 | 'componentWillUpdate', 13 | 'UNSAFE_componentWillUpdate', 14 | 'componentDidUpdate', 15 | 'componentWillUnmount', 16 | 'componentDidCatch', 17 | 'setState', 18 | 'forceUpdate', 19 | ]; 20 | 21 | export default function autoBindReact(self, {exclude = [], ...options} = {}) { 22 | options.exclude = [ 23 | ...exclude, 24 | ...excludedReactMethods, 25 | ]; 26 | 27 | return autoBind(self, options); 28 | } 29 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # auto-bind 2 | 3 | > Automatically bind methods to their class instance 4 | 5 | It also correctly binds inherited properties. 6 | 7 | If you're targeting Node.js 12 and later or the browser, you should consider using [class fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields#public_instance_fields) instead. 8 | 9 | ## Install 10 | 11 | ```sh 12 | npm install auto-bind 13 | ``` 14 | 15 | ## Usage 16 | 17 | ```js 18 | import autoBind from 'auto-bind'; 19 | 20 | class Unicorn { 21 | constructor(name) { 22 | this.name = name; 23 | autoBind(this); 24 | } 25 | 26 | message() { 27 | return `${this.name} is awesome!`; 28 | } 29 | } 30 | 31 | const unicorn = new Unicorn('Rainbow'); 32 | 33 | // Grab the method off the class instance 34 | const message = unicorn.message; 35 | 36 | // Still bound to the class instance 37 | message(); 38 | //=> 'Rainbow is awesome!' 39 | 40 | // Without `autoBind(this)`, the above would have resulted in 41 | message(); 42 | //=> Error: Cannot read property 'name' of undefined 43 | ``` 44 | 45 | ## API 46 | 47 | ### autoBind(self, options?) 48 | 49 | Bind methods in `self` to their class instance. 50 | 51 | Returns the `self` object. 52 | 53 | #### self 54 | 55 | Type: `object` 56 | 57 | An object with methods to bind. 58 | 59 | #### options 60 | 61 | Type: `object` 62 | 63 | ##### include 64 | 65 | Type: `Array` 66 | 67 | Bind only the given methods. 68 | 69 | ##### exclude 70 | 71 | Type: `Array` 72 | 73 | Bind methods except for the given methods. 74 | 75 | ### React 76 | 77 | Same as `autoBind` but excludes the default [React component methods](https://reactjs.org/docs/react-component.html). 78 | 79 | ```js 80 | import autoBindReact from 'auto-bind/react'; 81 | 82 | class Foo extends React.Component { 83 | constructor(props) { 84 | super(props); 85 | autoBindReact(this); 86 | } 87 | 88 | // … 89 | } 90 | ``` 91 | 92 | ## Related 93 | 94 | - [bind-methods](https://github.com/sindresorhus/bind-methods) - Bind all methods in an object to itself or a specified context 95 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import autoBindReact from './react.js'; 3 | import autoBind from './index.js'; 4 | 5 | test('autoBind()', t => { 6 | let bounded; 7 | 8 | class Unicorn { 9 | constructor(name) { 10 | this.name = name; 11 | bounded = autoBind(this); 12 | } 13 | 14 | message() { 15 | return `${this.name} is awesome!`; 16 | } 17 | 18 | get bad() { 19 | throw new Error('This getter somehow throws an error!'); 20 | } 21 | } 22 | 23 | const unicorn = new Unicorn('Rainbow'); 24 | t.is(bounded, unicorn); 25 | 26 | const {message} = unicorn; 27 | t.is(message(), 'Rainbow is awesome!'); 28 | }); 29 | 30 | test('include option', t => { 31 | class Unicorn { 32 | constructor(name) { 33 | this.name = name; 34 | autoBind(this, {include: ['bar']}); 35 | } 36 | 37 | foo() { 38 | return this.name; 39 | } 40 | 41 | bar() { 42 | return this.name; 43 | } 44 | } 45 | 46 | const {foo, bar} = new Unicorn('Rainbow'); 47 | 48 | t.throws(() => { 49 | foo(); 50 | }); 51 | 52 | t.is(bar(), 'Rainbow'); 53 | }); 54 | 55 | test('exclude option', t => { 56 | class Unicorn { 57 | constructor(name) { 58 | this.name = name; 59 | autoBind(this, {exclude: ['bar']}); 60 | } 61 | 62 | foo() { 63 | return this.name; 64 | } 65 | 66 | bar() { 67 | return this.name; 68 | } 69 | } 70 | 71 | const {foo, bar} = new Unicorn('Rainbow'); 72 | 73 | t.is(foo(), 'Rainbow'); 74 | 75 | t.throws(() => { 76 | bar(); 77 | }); 78 | }); 79 | 80 | test('symbol properties', t => { 81 | const messageSymbol = Symbol('message'); 82 | 83 | let bounded; 84 | 85 | class Unicorn { 86 | constructor(name) { 87 | this.name = name; 88 | bounded = autoBind(this); 89 | } 90 | 91 | [messageSymbol]() { 92 | return `${this.name} is awesome!`; 93 | } 94 | } 95 | 96 | const unicorn = new Unicorn('Rainbow'); 97 | t.is(bounded, unicorn); 98 | 99 | const message = unicorn[messageSymbol]; 100 | t.is(message(), 'Rainbow is awesome!'); 101 | }); 102 | 103 | test('binds inherited properties', t => { 104 | class Base { 105 | constructor(name) { 106 | this.name = name; 107 | } 108 | 109 | message() { 110 | return `${this.name} is awesome!`; 111 | } 112 | } 113 | 114 | class Base2 extends Base {} 115 | 116 | let bounded; 117 | class Unicorn extends Base2 { 118 | constructor(name) { 119 | super(name); 120 | bounded = autoBind(this); 121 | } 122 | } 123 | 124 | const unicorn = new Unicorn('Rainbow'); 125 | t.is(bounded, unicorn); 126 | 127 | const {message} = unicorn; 128 | t.is(message(), 'Rainbow is awesome!'); 129 | }); 130 | 131 | test('autoBindReact()', t => { 132 | class Unicorn { 133 | constructor(name) { 134 | this.name = name; 135 | autoBindReact(this); 136 | } 137 | 138 | componentWillMount() { 139 | return this.name; 140 | } 141 | 142 | foo() { 143 | return this.name; 144 | } 145 | } 146 | 147 | const {foo, componentWillMount} = new Unicorn('Rainbow'); 148 | 149 | t.throws(() => { 150 | componentWillMount(); 151 | }); 152 | 153 | t.is(foo(), 'Rainbow'); 154 | }); 155 | --------------------------------------------------------------------------------