Created
February 24, 2021 16:31
-
-
Save ManojSatishkumar/ceb7c1a1836a2698d400124d01784707 to your computer and use it in GitHub Desktop.
An example explicit hard binding in javascript
This file contains hidden or 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
// Explicit hard binding. | |
// Let's bind the calling function to the Function's prototype itself | |
if (!Function.prototype.bind2) { | |
Function.prototype.bind2 = function (o, args) { | |
return () => { | |
this.apply(o, [args]); | |
} | |
} | |
} | |
function foo(args) { | |
console.log(this.bar); | |
console.log(args); | |
} | |
var obj = { | |
bar: "bar1" | |
} | |
var obj2 = { | |
bar: 'bar2', | |
foo: function () { | |
foo.call(this) | |
} | |
} | |
foo = foo.bind2(obj, ['arg1', 'arg2']); | |
foo(); | |
// ----------------------------- | |
// 👨💻Author - Manoj Satishkumar | |
// ----------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment