Convenient replacement for Function.prototype.bind
Replace this
wow.much.dots.so.fancy.very.suit.bind(wow.much.dots.so.fancy.very);wow.much.dots.so.fancy.very.suit.bind(wow.much.dots.so.fancy.very,'!');varcached=wow.much.dots.so.fancy.very.suit.bind(wow.much.dots.so.fancy.very);With this
wow.much.dots.so.fancy.very.bound('suit');wow.much.dots.so.fancy.very.bound('suit','!');wow.much.dots.so.fancy.very.bound.suit;Let's make a bound suit()
varwow={much: {dots: {so: {fancy: {very: {suit: function(suffix){console.log(this.msg+(suffix||''));},msg: 'Many compliments'}}}}}};To print the following
'Many compliments!'Function.prototype.bind
varboundSuit=wow.much.dots.so.fancy.very.suit.bind(wow.much.dots.so.fancy.very,'!');boundSuit();// 'Many compliments!'Has all Function.prototype.bind features and a nicer syntax.
varboundSuit=wow.much.dots.so.fancy.very.bound('suit','!');boundSuit();// 'Many compliments!'Cached function binding. Clears cache on demand. No arguments binding.
varboundSuit=wow.much.dots.so.fancy.very.bound.suit;boundSuit('!');// 'Many compliments!'NOTE: Depends on ES6 Proxy, but works for non enumerable functions, unlike object-bound/property.js.
Cached function binding. Clears cache on demand. No arguments binding.
varboundSuit=wow.much.dots.so.fancy.very.bound.suit;boundSuit('!');// 'Many compliments!'Both property.js and proxy.js cache bound functions and can clear cache on demand.
With caching there is no need to store a reference to the bound function anymore.
varboundSuit1=wow.much.dots.so.fancy.very.bound.suit;varboundSuit2=wow.much.dots.so.fancy.very.bound.suit;// references the same function, always using .bound.suit gives the same resultboundSuit1===boundSuit2;// trueUse .bound.bound to get the new cached bound function.
varoldSuit=wow.much.dots.so.fancy.very.bound.suit;// .bound.bound clears the cache and returns new bound functionvarnewSuite=wow.much.dots.so.fancy.very.bound.bound.suit;oldSuit===boundSuit;// false// references the same function againnewSuite===wow.much.dots.so.fancy.very.bound.suit;// trueCached bound functions simplify working with event listeners.
classGreeter{constructor(el){this.el=el;this.msg='Hi!';// no need to store the reference to 'this.bound.hi' somewherethis.el.addEventListener('click',this.bound.hi);}off(){// remove event listener using the same 'this.bound.hi'this.el.removeEventListener('click',this.bound.hi);}hi(){console.log(this.msg);}}// get 'Hi!' on each click on the element :)vargreeter=newGreeter(element);// stop getting 'Hi!' on each click on the elementgreeter.off();