Created
October 25, 2016 20:13
-
-
Save gouegd/f720227723ce4f5cbd5b3f6575a9b824 to your computer and use it in GitHub Desktop.
Use ES6 Proxy to bind functions en masse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Say you have some methods in an object, and they rely on the context (this). | |
If you want to use them providing context, you typically would use Function.prototype.bind, apply or call | |
(maybe storing the bound methods in a new object, going through all the methods). | |
ES6 Proxies (only available on Node as I write this) provide an alternative to building a second object, | |
while still not having to pass the context on every call. | |
Is it better ? | |
Memory-wise, I'd say yes (though a hash of bound methods should seldom be a memory issue). | |
Performance-wise, I haven't tested it, and I wouldn't expect large differences (though Proxies are new and perhaps not optimised yet). | |
Anyway, I find it quite fun. | |
Keep in mind this is Node-only and not translatable to ES5. | |
**/ | |
const actions = { | |
say(who, what) { console.log(`${who} says ${what}`) }, | |
eat(who, meal) { console.log(`${who} ate some ${meal}`) } | |
} | |
const withCow = new Proxy(actions, { get(target, key){ if(typeof target[key]==='function') return target[key].bind(target, 'cow'); return target[key] } }) | |
withCow.say('moo') | |
// cow says moo | |
withCow.eat('herbs') | |
// cow ate some herbs | |
var methods = { | |
do(what){ console.log(`${this.getName()} does ${what}`) }, | |
save(where){ console.log(`saving data for ${this.getName()} in ${where}`) } | |
} | |
var greg = { | |
getName() { return 'Greg' } | |
} | |
methods.do('eat') | |
// TypeError: this.getName is not a function | |
const bind = who => methods => new Proxy(methods, { get(target, key){ if(typeof target[key]==='function') return target[key].bind(who); return target[key] } }); | |
const withGreg = bind(greg)(methods); | |
withGreg.do('eat'); | |
// Greg does eat | |
withGreg.save('a hut'); | |
// saving data for Greg in a hut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment