Skip to content

Instantly share code, notes, and snippets.

@yuriitaran
Last active January 25, 2022 20:13
Show Gist options
  • Save yuriitaran/c0c9e506148d10ed4db25d53b4563865 to your computer and use it in GitHub Desktop.
Save yuriitaran/c0c9e506148d10ed4db25d53b4563865 to your computer and use it in GitHub Desktop.
soft (weak) bind in JS
if (!Function.prototype.softBind) {
Function.prototype.softBind = function(obj) {
var fn = this,
curried = [].slice.call(arguments, 1),
bound = function bound() {
return fn.apply(
!this ||
(typeof window !== 'undefined' && this === window) ||
(typeof global !== 'undefined' && this === 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 <----
fooOBJ.call( obj3 ); // name: obj3 <----
setTimeout( obj2.foo, 10 ); // name: obj <---- weak bind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment