Skip to content

Instantly share code, notes, and snippets.

@var-bin
Last active July 19, 2018 13:39
Show Gist options
  • Save var-bin/89800ddd6f16815a649c09f4c2cc9d2a to your computer and use it in GitHub Desktop.
Save var-bin/89800ddd6f16815a649c09f4c2cc9d2a to your computer and use it in GitHub Desktop.
A simple `.bind` polyfill fo JavaScript

Modern JavaScript

const obj1 = {
  a: 'hello',
  say() {
    console.log(this.a, ...arguments);
  }
};

const obj2 = {
  a: 'buy'
};

// test
obj1.say.bind(obj2, 'friend', '!')();

The task is to implement a simple .bind polyfill for old browsers

  • Functional way
function _bind(func, ctx) {
  var slice = Array.prototype.slice;
  
  if (arguments.length < 2) {
    return func.apply(ctx);
  }
  
  return func.apply(ctx, slice.call(arguments, 2));
}

// test
_bind(obj1.say, obj2, 'ttt', 'aaa');
  • Extending Function.prototype
Function.prototype._bind = function(ctx) {
  const args = Array.prototype.slice.call(arguments, 1);
  const that = this;
  
  return function() {
    return that.apply(
      ctx,
      args.concat(Array.prototype.slice.call(arguments))
    );
  };
  
};

// test
obj1.say._bind(obj2, 'yyy', 'ccc')();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment