Skip to content

Instantly share code, notes, and snippets.

@domfarolino
Created November 14, 2016 00:48
Show Gist options
  • Save domfarolino/2ae4fa4f191abcf66c08d707d2d02488 to your computer and use it in GitHub Desktop.
Save domfarolino/2ae4fa4f191abcf66c08d707d2d02488 to your computer and use it in GitHub Desktop.
YDKJS Soft Bind Polyfill
/**
* The softBind "polyfill" is kind of like .bind(..) hard binding
* however it is slightly more flexible in that it can allow for
* `this` overrides with implicit, explicit, and `new` bindings.
* The default .bind(..) is less flexible only allows `this` overrides
* in situations where `new` is used.
*
* To use it, you pass in some default value for `this`. This value
* will only be used if the value of `this` at runtime is the global
* `window` object, or undefined (possibly strict mode). This means
* implict, explicit, and `new` bindings can override the default value
* of `this`.
*/
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;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment