I want to Create Polyfill for bind function of javascript for the browser which does not support bind function. Anyone, please tell how bind function is implemented in javascript.
In its simplest form, bind is just a wrapper for apply:
function bind(fn, thisObj) {
return function() {
return fn.apply(thisObj, arguments);
}
}
Implemented the basic functionality of bind by using apply. I called this method myBind, added it to the function prototype so that it's accessible by any function:
Function Implementation
Function.prototype.myBind = function() {
const callerFunction = this;
const [thisContext, ...args] = arguments;
return function() {
return callerFunction.apply(thisContext, args);
}
}
Usage: Can be used as a native bind function taking in the context and arguments.
function testMyBind(favColor) {
console.log(this.name, favColor); // Test, pink
}
const user = {
name: 'Test'
}
const bindedFunction = testMyBind.myBind(user, 'pink');
bindedFunction();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With