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.
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();
To keep things simple, while using the modern JavaScript:
Function.prototype.bind = function () {
return () => this.call(...arguments);
};
That's all there is to it.
Implemented the basic functionality using apply. Both bind function and bound function can accept arguments.
Function.prototype.bindPolyfill = function (obj, ...args) {
const func = this;
return function (...newArgs) {
return func.apply(obj, args.concat(newArgs));
};
};
Usage:
const employee = { id: '2'};
const getEmployee = function(name, dept){
console.log(this.id, name, dept);
};
const employee2 = getEmployee.bindPolyfill(employee, 'test');
employee2('Sales');
Function.prototype.bindPolyfill = function (newThis, ...args) {
return (...newArgs) => {
return this.apply(newThis, [...args, ...newArgs]);
};
};
// Usage
const employee = { id: '2' };
const getEmployee = function (name, dept) {
console.log(this.id, name, dept);
};
const employee2 = getEmployee.bindPolyfill(employee, 'test');
employee2('Sales'); // 2 test Sales
Function.prototype.customBind = function(ctx, ...args) {
const fn = this;
return function() {
return fn.apply(ctx, args);
}
}
A simple solution