Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
Aditya kumar Avatar asked Apr 30 '26 16:04

Aditya kumar


2 Answers

In its simplest form, bind is just a wrapper for apply:

function bind(fn, thisObj) {
  return function() {
    return fn.apply(thisObj, arguments);
  }
}
like image 81
georg Avatar answered May 03 '26 07:05

georg


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();
like image 43
ayushi nigam Avatar answered May 03 '26 06:05

ayushi nigam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!