'Javascript bind Function Implementation
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.
Solution 1:[1]
In its simplest form, bind is just a wrapper for apply:
function bind(fn, thisObj) {
return function() {
return fn.apply(thisObj, arguments);
}
}
Solution 2:[2]
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();
Solution 3:[3]
To keep things simple, while using the modern JavaScript:
Function.prototype.bind = function () {
return () => this.call(...arguments);
};
That's all there is to it.
Solution 4:[4]
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');
Solution 5:[5]
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
Solution 6:[6]
Function.prototype.customBind = function(ctx, ...args) {
const fn = this;
return function() {
return fn.apply(ctx, args);
}
}
A simple solution
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | georg |
| Solution 2 | ayushi nigam |
| Solution 3 | vitaly-t |
| Solution 4 | |
| Solution 5 | |
| Solution 6 | abhijithvijayan |
