Skip to content

Instantly share code, notes, and snippets.

@getify
Last active August 23, 2022 15:24
Show Gist options
  • Save getify/9043478 to your computer and use it in GitHub Desktop.
Save getify/9043478 to your computer and use it in GitHub Desktop.
function soft-binding
// 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
@FlorianSchaetz
Copy link

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.

@basherr
Copy link

basherr commented Aug 21, 2020

@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