3

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.

1

6 Answers 6

5

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

function bind(fn, thisObj) {
  return function() {
    return fn.apply(thisObj, arguments);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

2

To keep things simple, while using the modern JavaScript:

Function.prototype.bind = function () {
    return () => this.call(...arguments);
};

That's all there is to it.

Comments

1

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');

Comments

0
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

Comments

0
Function.prototype.customBind = function(ctx, ...args) {
    const fn = this;

    return function() {
        return fn.apply(ctx, args);
    }
}

A simple solution

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.