Skip to content

Instantly share code, notes, and snippets.

@valueof
Created February 27, 2013 00:29
Show Gist options
  • Save valueof/5043724 to your computer and use it in GitHub Desktop.
Save valueof/5043724 to your computer and use it in GitHub Desktop.
Destructuring with bound functions, yay/nay?
function bind(obj) {
let bound = {};
for (let key in obj) {
bound[key] = typeof obj[key] === "function" ? obj[key].bind(obj) : obj[key];
}
return bound;
}
function A() {
this.two = 2;
}
A.prototype.one = function () {
return this.two - 1;
};
A.prototype.sup = function () {
let {one, two} = bind(this);
return one() + two;
};
let a = new A();
a.sup(); // --> 3
@fitzgen
Copy link

fitzgen commented Feb 27, 2013

Wish there were a nice way to only bind functions you are going to use instead of all of them, but alas syntax > practicality amirite??

@victorporof
Copy link

The side effects are going to be sad when dealing with getters, since they'll be executed when you do typeof obj[key] === "function".

getOwnPropertyDescriptor all the things.

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