Last active
September 9, 2019 10:40
-
-
Save shekhardtu/1eded01d275e2dd9b089f2886ff9d9df to your computer and use it in GitHub Desktop.
polyfill of bind in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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