Skip to content

Instantly share code, notes, and snippets.

@shekhardtu
Last active September 9, 2019 10:40
Show Gist options
  • Save shekhardtu/1eded01d275e2dd9b089f2886ff9d9df to your computer and use it in GitHub Desktop.
Save shekhardtu/1eded01d275e2dd9b089f2886ff9d9df to your computer and use it in GitHub Desktop.
polyfill of bind in javascript
Function.prototype.myBind = function() {
var arg1 = [].slice.call(arguments);
var fn = this;
var that = arg1[0];
var param = arg1.slice(1);
return function() {
return fn.apply(that, param.concat(arguments));
}
}
// Example of working correctly
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.myBind(module);
var boundGetXBind = getX.bind(module);
boundGetX(); // 81
boundGetXBind(); // 81
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment