Skip to content

Instantly share code, notes, and snippets.

@ArtemAvramenko
Last active August 29, 2015 14:27
Show Gist options
  • Save ArtemAvramenko/3d7d7b16cf20dc20885d to your computer and use it in GitHub Desktop.
Save ArtemAvramenko/3d7d7b16cf20dc20885d to your computer and use it in GitHub Desktop.
Mix class with function.
/**
* Returns a function mixed with an object.
* @param obj - Object to mix.
* @param func - Target function.
*/
function mixWithFunc<T extends Function>(obj: { __proto__?}, func: T) {
var objProto = <{ constructor }>obj.__proto__;
var objClass = <{ __mixedProto__ }>objProto.constructor;
var proto = <typeof obj>objClass.__mixedProto__;
if (!proto) {
proto = {};
proto.__proto__ = objProto;
['call', 'apply', 'bind'].forEach(p => proto[p] = Function.prototype[p]);
objClass.__mixedProto__ = proto;
}
(<typeof obj>func).__proto__ = proto;
Object.getOwnPropertyNames(obj).forEach(p => func[p] = obj[p]);
return func;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment