Created
August 28, 2019 16:12
-
-
Save bitifet/5cfb2ba2f903e368597b2139b39f66f6 to your computer and use it in GitHub Desktop.
.softBind() - Rebindable [function].bind() alternative.
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
// Unless it could become ECMASCRIPT proposal best practice | |
// would be to use regular function in order to avoid polluting | |
// [function]'s prototype | |
// Twitter: https://twitter.com/bitifet/status/1166745132651220992?s=20 | |
const softBind = (function() { | |
const master = Symbol(); | |
return function softBind(self, ...args) { | |
const fn0 = self[master] || self; | |
const fn = fn0.bind(...args) | |
fn[master] = fn0; | |
return fn; | |
} | |
})(); | |
function showThis() { | |
console.log(this); | |
}; | |
const a = { name: "a" }; | |
const showA = softBind(showThis, a); | |
const b = { name: "b" }; | |
const showB = softBind(showA, b); | |
showA(); // { name: 'a' } | |
showB(); // { name: 'b' } |
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
// Conceptual example of (possible) future .softBind() method | |
// (Not a good practice thus pollutes function prototype with non standard methods) | |
// Twitter: https://twitter.com/bitifet/status/1166740427107700736?s=20 | |
(function() { | |
const fProto = Object.getPrototypeOf(function(){}); | |
const master = Symbol(); | |
fProto.softBind || ( | |
fProto.softBind = function softBind(...args) { | |
const fn0 = this[master] || this; | |
const fn = fn0.bind(...args) | |
fn[master] = fn0; | |
return fn; | |
} | |
); | |
})(); | |
function showThis() { | |
console.log(this); | |
}; | |
const a = { name: "a" }; | |
const showA = showThis.softBind(a); | |
const b = { name: "b" }; | |
const showB = showA.softBind(b); | |
showA(); // { name: 'a' } | |
showB(); // { name: 'b' } |
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
// Problem example: | |
// Twitter: https://twitter.com/bitifet/status/1166725486514528259?s=20 | |
function showThis() { | |
console.log(this); | |
}; | |
const a = { name: "a" }; | |
const showA = showThis.bind(a); | |
const b = { name: "b" }; | |
const showB = showA.bind(b); | |
showA(); // { name: 'a' } | |
showB(); // { name: 'a' } // !!!!!!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment