Skip to content

Instantly share code, notes, and snippets.

@anhldbk
Last active August 22, 2022 13:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anhldbk/782e13de7f79b07e556a029a9ce49fa3 to your computer and use it in GitHub Desktop.
Save anhldbk/782e13de7f79b07e556a029a9ce49fa3 to your computer and use it in GitHub Desktop.
Bind this for all methods in ES6 classes
'use strict';
class Binder {}
Binder.getAllMethods = function(instance, cls) {
return Object.getOwnPropertyNames(Object.getPrototypeOf(instance))
.filter(name => {
let method = instance[name];
return !(!(method instanceof Function) || method === cls);
});
}
Binder.bind = function(instance, cls) {
getAllMethods(instance, cls)
.forEach(mtd => {
instance[mtd] = instance[mtd].bind(instance);
})
}
module.exports = Binder;
@anhldbk
Copy link
Author

anhldbk commented Jun 2, 2016

To use the binder:

const Binder = require('./binder');
class Test{
    constructor(){
        // ...
        Binder.bind(this, Test)
    }
}

Copy link

ghost commented Dec 21, 2016

logical mind explosion:

return !(!(method instanceof Function) || method === cls);

ez logic

return method instanceof Function && method !== cls;

why? because De Morgan

!(a ∨ b) === !a ∧ !b

therefore

!(!a ∨ b) === a ∧ !b

(where is logical OR and is logical AND)

@davebrown
Copy link

thanks for this @anhldbk !

@ivangeorgiew
Copy link

This is cleaner (pun intended)

function bindMethods() {
    Object.getOwnPropertyNames(Object.getPrototypeOf(this))
        .map(key => {
            if (this[key] instanceof Function && key !== 'constructor')
                this[key] = this[key].bind(this)
        })
}

class Bla {
    constructor(name) {
        this.name = name
        
        bindMethods.call(this)        
    }
    
    greet () { console.log(`Hello, ${this.name}`) }
}

@TruDan
Copy link

TruDan commented Aug 22, 2022

@ivangeorgiew but what is the pun? I'm confused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment