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, '!');
var cached = 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()
var wow = { 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
var boundSuit = 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.
var boundSuit = wow.much.dots.so.fancy.very.bound('suit', '!');
boundSuit(); // 'Many compliments!'
Cached function binding. Clears cache on demand. No arguments binding.
var boundSuit = 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.
var boundSuit = 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.
var boundSuit1 = wow.much.dots.so.fancy.very.bound.suit;
var boundSuit2 = wow.much.dots.so.fancy.very.bound.suit;
// references the same function, always using .bound.suit gives the same result
boundSuit1 === boundSuit2; // true
Use .bound.bound
to get the new cached bound function.
var oldSuit = wow.much.dots.so.fancy.very.bound.suit;
// .bound.bound clears the cache and returns new bound function
var newSuite = wow.much.dots.so.fancy.very.bound.bound.suit;
oldSuit === boundSuit; // false
// references the same function again
newSuite === wow.much.dots.so.fancy.very.bound.suit; // true
Cached bound functions simplify working with event listeners.
class Greeter {
constructor(el) {
this.el = el;
this.msg = 'Hi!';
// no need to store the reference to 'this.bound.hi' somewhere
this.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 :)
var greeter = new Greeter(element);
// stop getting 'Hi!' on each click on the element
greeter.off();