Last active
August 23, 2022 15:24
-
-
Save getify/9043478 to your computer and use it in GitHub Desktop.
function soft-binding
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
// Modified based on: https://gist.github.com/getify/9043478/#comment-1210362 from @ZIJ | |
if (!Function.prototype.softBind) { | |
Function.prototype.softBind = function(obj) { | |
var fn = this; | |
// capture any curried parameters | |
var curried = [].slice.call( arguments, 1 ); | |
var bound = function() { | |
return fn.apply( | |
(!this || this === (window || global)) ? obj : this, | |
curried.concat.apply( curried, arguments ) | |
); | |
}; | |
bound.prototype = Object.create( fn.prototype ); | |
return bound; | |
}; | |
} | |
function foo() { | |
console.log("name: " + this.name); | |
} | |
var obj = { name: "obj" }, | |
obj2 = { name: "obj2" }, | |
obj3 = { name: "obj3" }; | |
var fooOBJ = foo.softBind(obj); | |
fooOBJ(); // name: obj | |
obj2.foo = foo.softBind(obj); | |
obj2.foo(); // name: obj2 <---- look!!! | |
fooOBJ.call(obj3); // name: obj3 <---- look! | |
setTimeout(obj2.foo,10); // name: obj <---- falls back to soft-binding |
@getify I would like to request one thing for the 2nd Edition book to keep the words as much simple as you can. This will help non-native speakers to understand at a much faster pace. However, I am really grateful to you for this work. Stay blessed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JS is full of little, hard to understand, very confusing details. That's what I like about it. Ups, no, that's what I totally hate about it. ;-)
Anyway, looking forward for edition 2 of your book, unfortunately the corresponding part does not seem to be there yet, so I have (for now) to rely on edition 1, which is still more in-depth than anything else I found so far.